package com.boot.web.serviceImpl;

import com.boot.utils.TimeUtil;
import com.boot.web.dao.*;
import com.boot.web.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.boot.web.service.OrdersCopyService;
import com.boot.base.serviceImpl.BaseServiceImpl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 订单业务层接口实现
 * @author 【zhouJie】
 * @date 2021-07-15 09:19:06
 */
@Service
public class OrdersCopyServiceImpl extends BaseServiceImpl<OrdersCopy> implements OrdersCopyService {

    private static final Logger logger = LoggerFactory.getLogger(OrdersCopyServiceImpl.class);

    @Autowired
    private OrdersCopyDao ordersCopyDao;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private ModeProductDao modeProductDao;

    @Autowired
    private CollageUserDao collageUserDao;

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private OrderDetailsDao orderDetailsDao;

    @Autowired
    private StoreShopDao storeShopDao;

    @Autowired
    private ClassifyDao classifyDao;

    @Autowired
    private SpecAttributeDao specAttributeDao;

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private AccountRecordDao accountRecordDao;

    @Autowired
    private CollageInRecord2Dao collageInRecord2Dao;

    @Autowired
    private CollageInRecord3Dao collageInRecord3Dao;

    @Autowired
    private UserCouponDao userCouponDao;

    @Autowired
    private CollageInRecord3CopyDao collageInRecord3CopyDao;

    @Autowired
    private SkuRelationDao skuRelationDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private FailRedPackDao failRedPackDao;

    @Autowired
    private CollageInRecord20Dao collageInRecord20Dao;

    /**
     * 处理团
     * @param collageMode
     * @param product
     * @param userId
     * @param totalAmount
     * @param totalPrice
     * @param consigneeName
     * @param fullAddress
     * @param consigneePhone
     * @param freight
     * @param couponPrice
     * @param couponQuantity
     * @param skuId
     * @param isSpellSelect
     * @param couponId
     * @param outTradeNo
     * @param tradeNo
     * @throws ParseException
     */
    @Override
    public void handleCollage(CollageMode collageMode, Product product, Integer userId, BigDecimal totalAmount, BigDecimal totalPrice,
                              String consigneeName, String fullAddress, String consigneePhone, BigDecimal freight, BigDecimal couponPrice,
                              Integer couponQuantity, Integer skuId, boolean isSpellSelect, Integer couponId, String outTradeNo, String tradeNo) throws ParseException {

        System.err.println("传递进来的couponQuantity ------------------------------------------------------------- " + couponQuantity);

        System.err.println("传递进来的skuId ------------------------------------------------------------- " + skuId);

        // 处理团信息
        ModeProduct modeProduct = modeProductDao.queryByProductIdByStatus(product.getId());
        if(modeProduct == null){
            // 创建新团
            ModeProduct newMP = new ModeProduct();
            newMP.setModeId(product.getCollageModeId());
            newMP.setProductId(product.getId());
            newMP.setStatus("0");
            newMP.setUpdateTime(new Date());
            modeProductDao.save(newMP);

            // 加入到当前团
            CollageUser newCU = new CollageUser();
            newCU.setModeProductId(newMP.getId());
            newCU.setUserId(userId);
            newCU.setUpdateTime(new Date());
            collageUserDao.save(newCU);

            // 创建订单
            Orders orders = new Orders();
            orders.setOrderNo(outTradeNo);
            orders.setTradeNo(tradeNo);
            orders.setTotalAmount(totalAmount);
            orders.setPayAmount(totalPrice);
            orders.setCouponAmount(couponPrice);
            orders.setFreight(freight);
            orders.setPayStatus("1");
            orders.setPayType("1");
            orders.setDealStatus("6"); // 等待开团
            orders.setRefundStatus("0");
            orders.setPrepayId("");
            orders.setCollageModeId(product.getCollageModeId());
            orders.setModeName(collageMode.getName());
            orders.setProductId(product.getId());
            orders.setModeProductId(newMP.getId());
            orders.setOrderPersonId(userId);
            orders.setConsigneeName(consigneeName);
            orders.setConsigneePhone(consigneePhone);
            orders.setAddress(fullAddress);
            orders.setUpdateTime(new Date());
            orders.setIsDel("0");
            orders.setIsRun("0");
            if(isSpellSelect){
                orders.setLastCollage("1");
            }else{
                orders.setLastCollage("0");
            }
            orders.setRemarks("无");
            ordersDao.save(orders);

            // 订单详情
            OrderDetails od = new OrderDetails();
            od.setOrderNo(orders.getOrderNo());
            od.setTradeNo(orders.getTradeNo());
            od.setStoreShopId(product.getStoreShopId());
            od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
            od.setClassifyId(product.getClassifyId());
            od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
            od.setProductId(product.getId());
            od.setProductType(product.getType());
            od.setProductImg(product.getImg());
            od.setProductName(product.getName());
            od.setProductCode(product.getProductCode());
            SkuRelation sku = skuRelationDao.queryById(skuId);
            od.setCostPrice(sku.getCostPrice());
            od.setRelationId(skuId);
            if(sku.getGroupRelation().contains(",")){
                String[] strings = sku.getGroupRelation().split(",");
                String str = "";
                for(int u = 0; u < strings.length; u++){
                    str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                }
                od.setSpecAttributeName(str.substring(0, str.length()-1));
            }else{
                od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
            }
            od.setQuantity(1);
            od.setUnitPrice(sku.getRetailPrice());
            od.setUpdateTime(new Date());
            orderDetailsDao.save(od);

            System.err.println("创建订单成功 ------------------------------------------------------------- 范围：modeProduct == null");

        }else{
            int quantity = collageMode.getPeopleQuantity(); // 18 or 9 or 6
            // 查询现在这个产品团里面有多少人了
            List<CollageUser> collageUserList = collageUserDao.queryByModeProductId(modeProduct.getId());
            int rowSize = collageUserList.size(); // 已参与人数
            if(rowSize < (quantity -1)){

                // 直接加入
                CollageUser newCU = new CollageUser();
                newCU.setModeProductId(modeProduct.getId());
                newCU.setUserId(userId);
                newCU.setUpdateTime(new Date());
                collageUserDao.save(newCU);

                // 创建订单
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalAmount);
                orders.setPayAmount(totalPrice);
                orders.setCouponAmount(couponPrice);
                orders.setFreight(freight);
                orders.setPayStatus("1");
                orders.setPayType("1");
                orders.setDealStatus("6"); // 等待开团
                orders.setRefundStatus("0");
                orders.setPrepayId("");
                orders.setCollageModeId(product.getCollageModeId());
                orders.setModeName(collageMode.getName());
                orders.setProductId(product.getId());
                orders.setModeProductId(modeProduct.getId()); // set老团的ID
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(new Date());
                orders.setIsDel("0");
                orders.setIsRun("0");
                if(isSpellSelect){
                    orders.setLastCollage("1");
                }else{
                    orders.setLastCollage("0");
                }
                orders.setRemarks("无");
                ordersDao.save(orders);

                // 订单详情
                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType());
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());
                od.setProductCode(product.getProductCode());
                SkuRelation sku = skuRelationDao.queryById(skuId);
                od.setCostPrice(sku.getCostPrice());
                od.setRelationId(skuId);
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                orderDetailsDao.save(od);

                System.err.println("创建订单成功 ------------------------------------------------------------- 范围：rowSize < (quantity -1)");

            }else if(rowSize == (quantity -1)){ // 需要重新生成新团，并随机一个人中奖，其他人执行退款

                // 加入当前团
                CollageUser newCU = new CollageUser();
                newCU.setModeProductId(modeProduct.getId());
                newCU.setUserId(userId);
                newCU.setUpdateTime(new Date());
                collageUserDao.save(newCU);

                // 修改老团
                modeProduct.setStatus("1"); // 拼团成功
                if(modeProduct.getModeId() == 2){
                    // 极乐桑巴,时间判断
                    boolean temp = judgeCollageIsHandle();
                    if(temp){
                        // 正常流程执行
                    }else{
                        modeProduct.setIsWaitFor("1"); // 设为等待中
                    }
                }
                modeProductDao.update(modeProduct);

                // 创建新团
                ModeProduct newMo = new ModeProduct();
                newMo.setUpdateTime(new Date());
                newMo.setProductId(product.getId());
                newMo.setModeId(collageMode.getId());
                newMo.setStatus("0");
                modeProductDao.save(newMo);

                // 创建订单
                Orders orders = new Orders();
                orders.setOrderNo(outTradeNo);
                orders.setTradeNo(tradeNo);
                orders.setTotalAmount(totalAmount);
                orders.setPayAmount(totalPrice);
                orders.setCouponAmount(couponPrice);
                orders.setFreight(freight);
                orders.setPayStatus("1");
                orders.setPayType("1");
                orders.setDealStatus("6"); // 等待开团
                orders.setRefundStatus("0");
                orders.setPrepayId("");
                orders.setCollageModeId(product.getCollageModeId());
                orders.setModeName(collageMode.getName());
                orders.setProductId(product.getId());
                orders.setModeProductId(modeProduct.getId()); // set老团的ID
                orders.setOrderPersonId(userId);
                orders.setConsigneeName(consigneeName);
                orders.setConsigneePhone(consigneePhone);
                orders.setAddress(fullAddress);
                orders.setUpdateTime(new Date());
                orders.setIsDel("0");
                orders.setIsRun("0");
                if(isSpellSelect){
                    orders.setLastCollage("1");
                }else{
                    orders.setLastCollage("0");
                }
                orders.setRemarks("无");
                ordersDao.save(orders);

                // 订单详情
                OrderDetails od = new OrderDetails();
                od.setOrderNo(orders.getOrderNo());
                od.setTradeNo(orders.getTradeNo());
                od.setStoreShopId(product.getStoreShopId());
                od.setStoreShopName(storeShopDao.queryById(product.getStoreShopId()).getName());
                od.setClassifyId(product.getClassifyId());
                od.setClassifyName(classifyDao.queryById(product.getClassifyId()).getName());
                od.setProductId(product.getId());
                od.setProductType(product.getType());
                od.setProductImg(product.getImg());
                od.setProductName(product.getName());
                od.setProductCode(product.getProductCode());
                SkuRelation sku = skuRelationDao.queryById(skuId);
                od.setCostPrice(sku.getCostPrice());
                od.setRelationId(skuId);
                if(sku.getGroupRelation().contains(",")){
                    String[] strings = sku.getGroupRelation().split(",");
                    String str = "";
                    for(int u = 0; u < strings.length; u++){
                        str += specAttributeDao.queryById(Integer.parseInt(strings[u])).getAttributeName() + "，";
                    }
                    od.setSpecAttributeName(str.substring(0, str.length()-1));
                }else{
                    od.setSpecAttributeName(specAttributeDao.queryById(Integer.parseInt(sku.getGroupRelation())).getAttributeName());
                }
                od.setQuantity(1);
                od.setUnitPrice(sku.getRetailPrice());
                od.setUpdateTime(new Date());
                orderDetailsDao.save(od);

                System.err.println("创建订单成功 ------------------------------------------------------------- 范围：rowSize == (quantity -1)");

                // 从老团中抽一个人中奖，其他人判断是否要进行自动退款
                if(modeProduct.getModeId() == 2){
                    // 极乐桑巴,时间判断
                    boolean temp = judgeCollageIsHandle();
                    if(temp){
                        List<Orders> ordersList = ordersDao.queryOrdersByCollageProductId(modeProduct.getId());
                        int ordersSize = ordersList.size();
                        if(ordersSize > 0){
                            Random random = new Random();
                            int n = random.nextInt(ordersSize); // 随机抽中一条数据
                            System.err.println("随机抽中一条数据 ------------------------------------------------------------- n == " + n);
                            for(int u = 0; u < ordersSize; u++){
                                Orders o = ordersList.get(u);
                                Customer customer = customerDao.queryById(o.getOrderPersonId());
                                if(u == n){
                                    // 添加销量
                                    product.setSales(product.getSales() + 1);
                                    productDao.update(product);

                                    // 中奖
                                    if(o.getCollageModeId() == 2){ // 十八人团
                                        o.setDealStatus("1"); // 待发货
                                    }else if(o.getCollageModeId() == 3){ // 九人团
                                        o.setDealStatus("7"); // 代售
                                    }else if(o.getCollageModeId() == 4){ // 溜溜溜
                                        o.setDealStatus("1"); // 待发货
                                    }else if(o.getCollageModeId() == 20){ // 速度与激情
                                        o.setDealStatus("1"); // 待发货
                                    }
                                    ordersDao.update(o);

                                    Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                    // 送3个极乐值
                                    acc.setBliss(acc.getBliss() + 3);
                                    // 送等额的积分
                                    int give = (int)Math.round(o.getPayAmount().doubleValue());
                                    acc.setIntegral(acc.getIntegral() + give);
                                    // 拼中也送红包余额
                                    acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher1()));
                                    accountDao.update(acc);

                                    AccountRecord ar3 = new AccountRecord();
                                    ar3.setIntoUserId(o.getOrderPersonId());
                                    ar3.setOrderNo(o.getOrderNo());
                                    ar3.setType("2");
                                    ar3.setSign("1");
                                    ar3.setUpdateTime(new Date());
                                    ar3.setAmount(new BigDecimal(3));
                                    ar3.setNowAmount(new BigDecimal(acc.getBliss()));
                                    ar3.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得极乐值：" + 3);
                                    accountRecordDao.save(ar3);

                                    AccountRecord ar3_1 = new AccountRecord();
                                    ar3_1.setIntoUserId(o.getOrderPersonId());
                                    ar3_1.setOrderNo(o.getOrderNo());
                                    ar3_1.setType("1");
                                    ar3_1.setSign("1");
                                    ar3_1.setUpdateTime(new Date());
                                    ar3_1.setAmount(new BigDecimal(give));
                                    ar3_1.setNowAmount(new BigDecimal(acc.getIntegral()));
                                    ar3_1.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得积分：" + give);
                                    accountRecordDao.save(ar3_1);

                                    AccountRecord ar3_2 = new AccountRecord();
                                    ar3_2.setIntoUserId(o.getOrderPersonId());
                                    ar3_2.setUpdateTime(new Date());
                                    ar3_2.setType("0");
                                    ar3_2.setAmount(product.getVoucher1());
                                    ar3_2.setNowAmount(acc.getVoucherBalance());
                                    ar3_2.setSign("1");
                                    ar3_2.setOrderNo(o.getOrderNo());
                                    ar3_2.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得红包余额：" + product.getVoucher1());
                                    accountRecordDao.save(ar3_2);

                                    // 处理参与拼团后的利润分配
                                    handleCollageProfit(userId, product.getVoucher1(), orders.getOrderNo());

                                    // TODO 这里这里
                                    // 极乐桑巴
                                    if(o.getCollageModeId() == 2){
                                        // 判断当前产品是否满六次，执行全额退款
                                        CollageInRecord2 cir2 = collageInRecord2Dao.queryCir2ByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                        if(cir2 == null){
                                            // 第一次中当前产品
                                            CollageInRecord2 newCir2 = new CollageInRecord2();
                                            newCir2.setModeId(o.getCollageModeId());
                                            newCir2.setProductId(o.getProductId());
                                            newCir2.setUserId(o.getOrderPersonId());
                                            newCir2.setStatus("0");
                                            newCir2.setTotalQuantity(1);
                                            newCir2.setPayAmount(o.getPayAmount());
                                            newCir2.setUpdateTime(new Date());
                                            collageInRecord2Dao.save(newCir2);
                                        }else{
                                            // TODO 将6改成3
                                            if(cir2.getTotalQuantity() < 3){
                                                // 继续累积
                                                cir2.setPayAmount(cir2.getPayAmount().add(o.getPayAmount()));
                                                cir2.setTotalQuantity(cir2.getTotalQuantity() + 1);
                                                cir2.setUpdateTime(new Date());
                                                collageInRecord2Dao.update(cir2);
                                            }else{
                                                // 满足六次，退钱六次的钱
                                                cir2.setStatus("1");
                                                cir2.setUpdateTime(new Date());
                                                collageInRecord2Dao.update(cir2);

                                                Account accCir = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                                accCir.setVoucherBalance(accCir.getVoucherBalance().add(cir2.getPayAmount()));
                                                accountDao.update(accCir);

                                                AccountRecord arCir = new AccountRecord();
                                                arCir.setIntoUserId(o.getOrderPersonId());
                                                arCir.setUpdateTime(new Date());
                                                arCir.setType("0");
                                                arCir.setAmount(cir2.getPayAmount());
                                                arCir.setNowAmount(accCir.getVoucherBalance());
                                                arCir.setSign("1");
                                                arCir.setOrderNo(o.getOrderNo());
                                                // TODO 将6改成3
                                                arCir.setInfo(customer.getAgentCode() + "参团成功! 累积拼中产品三次,获得广告补贴为：" + cir2.getPayAmount());
                                                accountRecordDao.save(arCir);

                                                // 送共享券
                                                UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir2.getUserId(), 2);
                                                if(userCoupon != null){
                                                    userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                    userCoupon.setUpdateTime(new Date());
                                                    userCouponDao.update(userCoupon);

                                                    AccountRecord ar1 = new AccountRecord();
                                                    ar1.setIntoUserId(cir2.getUserId());
                                                    ar1.setUpdateTime(new Date());
                                                    ar1.setType("6");
                                                    ar1.setAmount(new BigDecimal(1));
                                                    ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                    ar1.setSign("1");
                                                    // TODO 将6改成3
                                                    ar1.setInfo(customerDao.queryById(cir2.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                    accountRecordDao.save(ar1);
                                                }else{
                                                    UserCoupon newUc = new UserCoupon();
                                                    newUc.setQuantity(1);
                                                    newUc.setUpdateTime(new Date());
                                                    newUc.setCouponId(2);
                                                    newUc.setUserId(cir2.getUserId());
                                                    userCouponDao.save(newUc);

                                                    AccountRecord ar2 = new AccountRecord();
                                                    ar2.setIntoUserId(cir2.getUserId());
                                                    ar2.setUpdateTime(new Date());
                                                    ar2.setType("6");
                                                    ar2.setAmount(new BigDecimal(1));
                                                    ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                    ar2.setSign("1");
                                                    // TODO 将6改成3
                                                    ar2.setInfo(customerDao.queryById(cir2.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                    accountRecordDao.save(ar2);
                                                }

                                                // 存下第七次
                                                CollageInRecord2 newCir7 = new CollageInRecord2();
                                                newCir7.setModeId(o.getCollageModeId());
                                                newCir7.setProductId(o.getProductId());
                                                newCir7.setUserId(o.getOrderPersonId());
                                                newCir7.setStatus("0");
                                                newCir7.setTotalQuantity(1);
                                                newCir7.setPayAmount(o.getPayAmount());
                                                newCir7.setUpdateTime(new Date());
                                                collageInRecord2Dao.save(newCir7);
                                            }
                                        }

                                        // 判断当前拼团模式中是否存在满足六次的，有就执行退款
                                        // TODO 将6改成3
                                        CollageInRecord2 cir2_1 = collageInRecord2Dao.queryCir2ByIds_1(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                        if(cir2_1 != null){
                                            // 满足六次，退钱六次的钱
                                            cir2_1.setStatus("1");
                                            cir2_1.setUpdateTime(new Date());
                                            collageInRecord2Dao.update(cir2_1);

                                            Account accCir_1 = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                            accCir_1.setVoucherBalance(accCir_1.getVoucherBalance().add(cir2_1.getPayAmount()));
                                            accountDao.update(accCir_1);

                                            AccountRecord arCir_1 = new AccountRecord();
                                            arCir_1.setIntoUserId(o.getOrderPersonId());
                                            arCir_1.setUpdateTime(new Date());
                                            arCir_1.setType("0");
                                            arCir_1.setAmount(cir2_1.getPayAmount());
                                            arCir_1.setNowAmount(accCir_1.getVoucherBalance());
                                            arCir_1.setSign("1");
                                            arCir_1.setOrderNo(o.getOrderNo());
                                            // TODO 将6改成3
                                            arCir_1.setInfo(customer.getAgentCode() + "参团成功! 累积拼中产品三次,获得广告补贴为：" + cir2_1.getPayAmount());
                                            accountRecordDao.save(arCir_1);

                                            // 送共享券
                                            UserCoupon userCoupon1 = userCouponDao.queryByUserIdAndCouponId(cir2_1.getUserId(), 2);
                                            if(userCoupon1 != null){
                                                userCoupon1.setQuantity(userCoupon1.getQuantity() + 1);
                                                userCoupon1.setUpdateTime(new Date());
                                                userCouponDao.update(userCoupon1);

                                                AccountRecord ar1 = new AccountRecord();
                                                ar1.setIntoUserId(cir2_1.getUserId());
                                                ar1.setUpdateTime(new Date());
                                                ar1.setType("6");
                                                ar1.setAmount(new BigDecimal(1));
                                                ar1.setNowAmount(new BigDecimal(userCoupon1.getQuantity()));
                                                ar1.setSign("1");
                                                // TODO 将6改成3
                                                ar1.setInfo(customerDao.queryById(cir2_1.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar1);
                                            }else{
                                                UserCoupon newUc = new UserCoupon();
                                                newUc.setQuantity(1);
                                                newUc.setUpdateTime(new Date());
                                                newUc.setCouponId(2);
                                                newUc.setUserId(cir2_1.getUserId());
                                                userCouponDao.save(newUc);

                                                AccountRecord ar2 = new AccountRecord();
                                                ar2.setIntoUserId(cir2_1.getUserId());
                                                ar2.setUpdateTime(new Date());
                                                ar2.setType("6");
                                                ar2.setAmount(new BigDecimal(1));
                                                ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                ar2.setSign("1");
                                                // TODO 将6改成3
                                                ar2.setInfo(customerDao.queryById(cir2_1.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar2);
                                            }
                                        }

                                    }

                                }else{
                                    // 是否退款
                                    if("1".equals(o.getLastCollage())){

                                        // 当前订单转移到 OrdersCopy
                                        OrdersCopy oc = new OrdersCopy();
                                        oc.setId(o.getId());
                                        oc.setOrderNo(o.getOrderNo());
                                        oc.setTradeNo(o.getTradeNo());
                                        oc.setTotalAmount(o.getTotalAmount());
                                        oc.setFreight(o.getFreight());
                                        oc.setCollageModeId(o.getCollageModeId());
                                        oc.setOrderPersonId(o.getOrderPersonId());
                                        oc.setLastCollage(o.getLastCollage());
                                        oc.setConsigneeName(o.getConsigneeName());
                                        oc.setConsigneePhone(o.getConsigneePhone());
                                        oc.setAddress(o.getAddress());
                                        oc.setUpdateTime(new Date());
                                        oc.setPayAmount(o.getPayAmount());
                                        oc.setCouponAmount(o.getCouponAmount());
                                        oc.setModeProductId(o.getModeProductId());
                                        oc.setProductId(o.getProductId());
                                        oc.setCouponId(couponId);
                                        oc.setSkuId(orderDetailsDao.queryByOrderNo(o.getOrderNo()).getRelationId());
                                        BigDecimal couponAmount = null;
                                        if(o.getCouponAmount() == null){
                                            couponAmount = new BigDecimal(0);
                                        }else{
                                            couponAmount = o.getCouponAmount();
                                        }
                                        if(couponAmount.doubleValue() > 0){
                                            int quantity1 = (int) (couponAmount.doubleValue() / 9.9);
                                            oc.setCouponQuantity(quantity1);
                                        }else{
                                            oc.setCouponQuantity(0);
                                        }
                                        ordersCopyDao.save(oc);

                                        // 给个红包
//                                        Account accN = accountDao.queryAccountByUserId(o.getOrderPersonId());
//                                        Product p = productDao.queryById(o.getProductId());
//                                        accN.setVoucherBalance(accN.getVoucherBalance().add(p.getVoucher()));
//                                        accountDao.update(accN);
//
//                                        AccountRecord ar1_2 = new AccountRecord();
//                                        ar1_2.setIntoUserId(o.getOrderPersonId());
//                                        ar1_2.setUpdateTime(new Date());
//                                        ar1_2.setType("0");
//                                        ar1_2.setAmount(p.getVoucher());
//                                        ar1_2.setNowAmount(accN.getVoucherBalance());
//                                        ar1_2.setSign("1");
//                                        ar1_2.setOrderNo(o.getOrderNo());
//                                        ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + p.getVoucher());
//                                        accountRecordDao.save(ar1_2);

                                        FailRedPack frp = new FailRedPack();
                                        frp.setOrderNo(o.getOrderNo());
                                        frp.setPrizeMoney(product.getVoucher());
                                        frp.setStatus("2"); // 未开红包
                                        frp.setUpdateTime(new Date());
                                        frp.setUserId(o.getOrderPersonId());
                                        frp.setMode("0");
                                        failRedPackDao.save(frp);

                                        // 处理参与拼团后的利润分配
                                        // handleCollageProfit(o.getOrderPersonId(), p.getVoucher(), o.getOrderNo());

                                    }else{
                                        // 执行退款(退到余额)退券 把每个人领取到的红包进行分润
                                        o.setDealStatus("4"); // 交易关闭
                                        o.setRefundStatus("2"); // 退款成功
                                        o.setPayStatus("3"); // 已退款
                                        ordersDao.update(o);

                                        Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                        acc.setVoucherBalance(acc.getVoucherBalance().add(o.getPayAmount()));
                                        accountDao.update(acc);

                                        AccountRecord ar1_1 = new AccountRecord();
                                        ar1_1.setIntoUserId(o.getOrderPersonId());
                                        ar1_1.setUpdateTime(new Date());
                                        ar1_1.setType("0");
                                        ar1_1.setAmount(o.getPayAmount());
                                        ar1_1.setNowAmount(acc.getVoucherBalance());
                                        ar1_1.setSign("1");
                                        ar1_1.setOrderNo(o.getOrderNo());
                                        ar1_1.setInfo(customer.getAgentCode() + "参团成功! 未抽中,支付金额退回至余额：" + o.getPayAmount());
                                        accountRecordDao.save(ar1_1);

                                        if(couponQuantity > 0){
                                            UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(o.getOrderPersonId(), couponId);
                                            if(uc != null){
                                                uc.setQuantity(uc.getQuantity() + couponQuantity);
                                                userCouponDao.update(uc);

                                                AccountRecord ar2 = new AccountRecord();
                                                ar2.setIntoUserId(o.getOrderPersonId());
                                                ar2.setUpdateTime(new Date());
                                                ar2.setType("5"); // 拼团券
                                                ar2.setAmount(new BigDecimal(couponQuantity));
                                                ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                                                ar2.setSign("1");
                                                ar2.setOrderNo(o.getOrderNo());
                                                ar2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,拼团券退回：" + couponQuantity);
                                                accountRecordDao.save(ar2);
                                            }
                                        }

                                        // acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher()));
                                        // accountDao.update(acc);

//                                        AccountRecord ar1_2 = new AccountRecord();
//                                        ar1_2.setIntoUserId(o.getOrderPersonId());
//                                        ar1_2.setUpdateTime(new Date());
//                                        ar1_2.setType("0");
//                                        ar1_2.setAmount(product.getVoucher());
//                                        ar1_2.setNowAmount(acc.getVoucherBalance());
//                                        ar1_2.setSign("1");
//                                        ar1_2.setOrderNo(o.getOrderNo());
//                                        ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + product.getVoucher());
//                                        accountRecordDao.save(ar1_2);

                                        FailRedPack frp = new FailRedPack();
                                        frp.setOrderNo(o.getOrderNo());
                                        frp.setPrizeMoney(product.getVoucher());
                                        frp.setStatus("2"); // 未开红包
                                        frp.setUpdateTime(new Date());
                                        frp.setUserId(o.getOrderPersonId());
                                        frp.setMode("0");
                                        failRedPackDao.save(frp);

                                        // 处理参与拼团后的利润分配
                                        // handleCollageProfit(userId, product.getVoucher(), orders.getOrderNo());

                                    }
                                }
                            }
                        }

                    }else {

                        // 极乐桑巴 每天 10:00-10:20    16:00-16:20    21:30-21:50  统一处理团

                    }
                }else{
                    // 进入九人拼或六人拼
                    List<Orders> ordersList = ordersDao.queryOrdersByCollageProductId(modeProduct.getId());
                    int ordersSize = ordersList.size();
                    if(ordersSize > 0){
                        Random random = new Random();
                        int n = random.nextInt(ordersSize); // 随机抽中一条数据
                        System.err.println("随机抽中一条数据 ------------------------------------------------------------- n == " + n);
                        for(int u = 0; u < ordersSize; u++){
                            Orders o = ordersList.get(u);
                            Customer customer = customerDao.queryById(o.getOrderPersonId());
                            if(u == n){
                                // 添加销量
                                product.setSales(product.getSales() + 1);
                                productDao.update(product);

                                // 中奖
                                if(o.getCollageModeId() == 2){ // 十八人团
                                    o.setDealStatus("1"); // 待发货
                                }else if(o.getCollageModeId() == 3){ // 九人团
                                    o.setDealStatus("7"); // 代售
                                }else if(o.getCollageModeId() == 4){ // 溜溜溜
                                    o.setDealStatus("1"); // 待发货
                                }else if(o.getCollageModeId() == 20){ // 速度与激情
                                    o.setDealStatus("1"); // 待发货
                                }
                                ordersDao.update(o);

                                Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                // 送3个极乐值
                                acc.setBliss(acc.getBliss() + 3);
                                // 送等额的积分
                                int give = (int)Math.round(o.getPayAmount().doubleValue());
                                acc.setIntegral(acc.getIntegral() + give);
                                // 拼中也送红包余额
                                acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher1()));
                                accountDao.update(acc);

                                AccountRecord ar3 = new AccountRecord();
                                ar3.setIntoUserId(o.getOrderPersonId());
                                ar3.setOrderNo(o.getOrderNo());
                                ar3.setType("2");
                                ar3.setSign("1");
                                ar3.setUpdateTime(new Date());
                                ar3.setAmount(new BigDecimal(3));
                                ar3.setNowAmount(new BigDecimal(acc.getBliss()));
                                ar3.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得极乐值：" + 3);
                                accountRecordDao.save(ar3);

                                AccountRecord ar3_1 = new AccountRecord();
                                ar3_1.setIntoUserId(o.getOrderPersonId());
                                ar3_1.setOrderNo(o.getOrderNo());
                                ar3_1.setType("1");
                                ar3_1.setSign("1");
                                ar3_1.setUpdateTime(new Date());
                                ar3_1.setAmount(new BigDecimal(give));
                                ar3_1.setNowAmount(new BigDecimal(acc.getIntegral()));
                                ar3_1.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得积分：" + give);
                                accountRecordDao.save(ar3_1);

                                AccountRecord ar3_2 = new AccountRecord();
                                ar3_2.setIntoUserId(o.getOrderPersonId());
                                ar3_2.setUpdateTime(new Date());
                                ar3_2.setType("0");
                                ar3_2.setAmount(product.getVoucher1());
                                ar3_2.setNowAmount(acc.getVoucherBalance());
                                ar3_2.setSign("1");
                                ar3_2.setOrderNo(o.getOrderNo());
                                ar3_2.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得红包余额：" + product.getVoucher1());
                                accountRecordDao.save(ar3_2);

                                // 处理参与拼团后的利润分配
                                handleCollageProfit(userId, product.getVoucher1(), orders.getOrderNo());

                                // TODO 这里这里
                                // 喜欢就拼
                                if(o.getCollageModeId() == 3){
                                    // 判断当前产品是否满十二次，执行每月代售
                                    // 查看当前模式当前产品当前人 一共中了多少条
                                    List<CollageInRecord3> cir3List = collageInRecord3Dao.queryCir3ByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                    List<CollageInRecord3> cir3List_copy = cir3List;
                                    int cir3Size = cir3List.size();
                                    if(cir3Size > 0){
                                        // TODO 将12改成3
                                        if(cir3Size < 3){
                                            // 未满十二次直接加一条
                                            CollageInRecord3 newCir3 = new CollageInRecord3();
                                            newCir3.setModeId(o.getCollageModeId());
                                            newCir3.setProductId(o.getProductId());
                                            newCir3.setUserId(o.getOrderPersonId());
                                            newCir3.setStatus("0"); // 未返还
                                            newCir3.setIsTake("1"); // 还能提货
                                            newCir3.setOrderNo(o.getOrderNo());
                                            newCir3.setPayAmount(o.getPayAmount());
                                            newCir3.setUpdateTime(o.getUpdateTime());
                                            collageInRecord3Dao.save(newCir3);

                                            // 查看CollageInRecord3Copy当前模式当前产品当前人一共累计有多少
                                            CollageInRecord3Copy cir3Copy = collageInRecord3CopyDao.queryByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            if(cir3Copy == null){
                                                // 创建并累计一次
                                                CollageInRecord3Copy newCir3Copy = new CollageInRecord3Copy();
                                                newCir3Copy.setModeId(o.getCollageModeId());
                                                newCir3Copy.setProductId(o.getProductId());
                                                newCir3Copy.setUserId(o.getOrderPersonId());
                                                newCir3Copy.setTotalQuantity(1);
                                                newCir3Copy.setStatus("0");
                                                newCir3Copy.setPayAmount(o.getPayAmount());
                                                newCir3Copy.setUpdateTime(new Date());
                                                collageInRecord3CopyDao.save(newCir3Copy);
                                            }else{
                                                // 直接累计一次
                                                cir3Copy.setTotalQuantity(cir3Copy.getTotalQuantity() + 1);
                                                cir3Copy.setPayAmount(cir3Copy.getPayAmount().add(o.getPayAmount()));
                                                cir3Copy.setUpdateTime(new Date());
                                                collageInRecord3CopyDao.update(cir3Copy);
                                            }

                                        }else{
                                            // 满足十二次了
                                            // 查看当前模式当前产品当前人下面有多少个代售 还没有返还能提货的条数
                                            List<CollageInRecord3> getCir3List = collageInRecord3Dao.queryCir3ByIds_1(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            if(getCir3List.size() > 0){
                                                CollageInRecord3 getCir3 = getCir3List.get(0);
                                                CollageInRecord3 getCir3_1 = null;
                                                if(getCir3List.size() > 1){
                                                    getCir3_1 = getCir3List.get(1);
                                                }
                                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                                String time = df.format(o.getUpdateTime());
                                                boolean temp = false;
                                                for(int v = 0; v < cir3Size; v++){
                                                    CollageInRecord3 cir3 = cir3List.get(v);
                                                    if(getCir3.getId() == cir3.getId()){ // 未返并能提货中的第一个去匹配所有的得到一条数据进行代售

                                                        cir3.setStatus("1"); // 已返还
                                                        cir3.setEstimateReturn(time); // 当天返回一个代售   yyyy-MM-dd  时间为当下返回的代售标记

                                                        // 退钱
                                                        Account acc3 = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                                        acc3.setVoucherBalance(acc3.getVoucherBalance().add(cir3.getPayAmount()));
                                                        accountDao.update(acc3);

                                                        AccountRecord ar = new AccountRecord();
                                                        ar.setIntoUserId(o.getOrderPersonId());
                                                        ar.setUpdateTime(new Date());
                                                        ar.setType("0");
                                                        ar.setAmount(cir3.getPayAmount());
                                                        ar.setNowAmount(acc3.getVoucherBalance());
                                                        ar.setSign("1");
                                                        ar.setOrderNo(o.getOrderNo());
                                                        // TODO 将12改成3
                                                        ar.setInfo(customer.getAgentCode() + "参团成功! 累计抽中已满三次, 当下返回一个代售：" + cir3.getPayAmount());
                                                        accountRecordDao.save(ar);

                                                        // 修改订单信息
                                                        Orders orders1 = ordersDao.queryByOrderNo(cir3.getOrderNo());
                                                        if(orders1 != null){
                                                            orders1.setDealStatus("4"); // 交易关闭
                                                            orders1.setRefundStatus("2"); // 退款成功
                                                            orders1.setPayStatus("3"); // 已退款
                                                            ordersDao.update(orders1);
                                                        }

                                                        // 送共享券
                                                        UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir3.getUserId(), 2); // 2 是共享券
                                                        if(userCoupon != null){
                                                            userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                            userCoupon.setUpdateTime(new Date());
                                                            userCouponDao.update(userCoupon);

                                                            AccountRecord ar1 = new AccountRecord();
                                                            ar1.setIntoUserId(cir3.getUserId());
                                                            ar1.setUpdateTime(new Date());
                                                            ar1.setType("6");
                                                            ar1.setAmount(new BigDecimal(1));
                                                            ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                            ar1.setSign("1");
                                                            // TODO 将12改成3
                                                            ar1.setInfo(customerDao.queryById(cir3.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar1);
                                                        }else{
                                                            UserCoupon newUc = new UserCoupon();
                                                            newUc.setQuantity(1);
                                                            newUc.setUpdateTime(new Date());
                                                            newUc.setCouponId(2);
                                                            newUc.setUserId(cir3.getUserId());
                                                            userCouponDao.save(newUc);

                                                            AccountRecord ar2 = new AccountRecord();
                                                            ar2.setIntoUserId(cir3.getUserId());
                                                            ar2.setUpdateTime(new Date());
                                                            ar2.setType("6");
                                                            ar2.setAmount(new BigDecimal(1));
                                                            ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                            ar2.setSign("1");
                                                            // TODO 将12改成3
                                                            ar2.setInfo(customerDao.queryById(cir3.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar2);
                                                        }

                                                        // 查看当前模式当前产品当前人 是否 我要自提过
                                                        List<CollageInRecord3> getCir3List_1 = collageInRecord3Dao.queryCir3ByIds_1_1(cir3.getModeId(), cir3.getProductId(), cir3.getUserId());
                                                        if(getCir3List_1.size() > 0){
                                                            temp = false;
                                                            // 已经提过货了
                                                        }else{
                                                            temp = true;
                                                            // 需要强制一个代售成为发货单
                                                        }

                                                    }
                                                    cir3.setIsTake("0"); // 不能提货
                                                    cir3.setEndTime(o.getUpdateTime()); // set第13个的时间
                                                    collageInRecord3Dao.update(cir3);
                                                }

                                                if(temp){
                                                    if(getCir3_1 != null){
                                                        for(int b = 0; b < cir3List_copy.size(); b++){
                                                            CollageInRecord3 cir3_1 = cir3List_copy.get(b);
                                                            if(getCir3_1.getId() == cir3_1.getId()) {
                                                                // 修改订单信息
                                                                Orders orders1_1 = ordersDao.queryByOrderNo(cir3_1.getOrderNo());
                                                                if(orders1_1 != null){
                                                                    orders1_1.setDealStatus("1"); // 待发货
                                                                    orders1_1.setRemarks("累计抽中已满三次, 当下返还一个代售并且再发货一个代售");
                                                                    ordersDao.update(orders1_1);

                                                                    cir3_1.setStatus("1"); // 已返还
                                                                    cir3_1.setEstimateReturn(time); // 当天再返回一个代售
                                                                    collageInRecord3Dao.update(cir3_1);
                                                                }
                                                            }
                                                        }
                                                    }else{
                                                        System.err.println("没有代售了!!!");
                                                    }
                                                }

                                            }

                                            // 将累计的总体修改为已退
                                            CollageInRecord3Copy isCir3Copy = collageInRecord3CopyDao.queryByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            if(isCir3Copy != null){
                                                isCir3Copy.setUpdateTime(new Date());
                                                isCir3Copy.setStatus("1");
                                                collageInRecord3CopyDao.update(isCir3Copy);
                                            }

                                            // 将剩余的代售进行定时，每月返回一个
                                            List<CollageInRecord3> cir3List_1 = collageInRecord3Dao.queryCir3ByIds_2(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            int size = cir3List_1.size();
                                            if(size > 0){
                                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                                String time = df.format(o.getUpdateTime());
                                                TimeUtil timeUtil = new TimeUtil();
                                                String[] strings = timeUtil.getNextMonth_for(time, size);
                                                for(int z = 0; z < strings.length; z++){
                                                    for(int x = 0; x < size; x++){
                                                        if(z == x){
                                                            CollageInRecord3 cir = cir3List_1.get(x);
                                                            cir.setEstimateReturn(strings[z]);
                                                            collageInRecord3Dao.update(cir);
                                                        }
                                                    }
                                                }
                                            }

                                            // 创建第13个
                                            CollageInRecord3 newCir3 = new CollageInRecord3();
                                            newCir3.setModeId(o.getCollageModeId());
                                            newCir3.setProductId(o.getProductId());
                                            newCir3.setUserId(o.getOrderPersonId());
                                            newCir3.setStatus("0");
                                            newCir3.setIsTake("1");
                                            newCir3.setOrderNo(o.getOrderNo());
                                            newCir3.setPayAmount(o.getPayAmount());
                                            newCir3.setUpdateTime(o.getUpdateTime());
                                            collageInRecord3Dao.save(newCir3);

                                        }

                                    }else{
                                        // 第一次拼中当前产品
                                        CollageInRecord3 newCir4 = new CollageInRecord3();
                                        newCir4.setModeId(o.getCollageModeId());
                                        newCir4.setProductId(o.getProductId());
                                        newCir4.setUserId(o.getOrderPersonId());
                                        newCir4.setStatus("0"); // 未返还
                                        newCir4.setIsTake("1"); // 还能提货
                                        newCir4.setOrderNo(o.getOrderNo());
                                        newCir4.setPayAmount(o.getPayAmount());
                                        newCir4.setUpdateTime(o.getUpdateTime());
                                        collageInRecord3Dao.save(newCir4);

                                        // 查看CollageInRecord3Copy当前模式当前产品当前人一共累计有多少
                                        CollageInRecord3Copy cir3Copy = collageInRecord3CopyDao.queryByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                        if(cir3Copy == null){
                                            // 创建并累计一次
                                            CollageInRecord3Copy newCir3Copy = new CollageInRecord3Copy();
                                            newCir3Copy.setModeId(o.getCollageModeId());
                                            newCir3Copy.setProductId(o.getProductId());
                                            newCir3Copy.setUserId(o.getOrderPersonId());
                                            newCir3Copy.setTotalQuantity(1);
                                            newCir3Copy.setStatus("0");
                                            newCir3Copy.setPayAmount(o.getPayAmount());
                                            newCir3Copy.setUpdateTime(new Date());
                                            collageInRecord3CopyDao.save(newCir3Copy);
                                        }else{
                                            // 直接累计一次
                                            cir3Copy.setTotalQuantity(cir3Copy.getTotalQuantity() + 1);
                                            cir3Copy.setPayAmount(cir3Copy.getPayAmount().add(o.getPayAmount()));
                                            cir3Copy.setUpdateTime(new Date());
                                            collageInRecord3CopyDao.update(cir3Copy);
                                        }

                                    }


                                    // TODO 判断当前拼团模式中是否存在满足十二次的 // TODO 将12改成3
                                    CollageInRecord3Copy cir3Copy12 = collageInRecord3CopyDao.queryByIds_1(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                    if(cir3Copy12 != null){
                                        // 满足十二次了
                                        List<CollageInRecord3> getCir3List = collageInRecord3Dao.queryCir3ByIds_1(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                        if(getCir3List.size() > 0){
                                            CollageInRecord3 getCir3 = getCir3List.get(0);
                                            CollageInRecord3 getCir3_1 = null;
                                            if(getCir3List.size() > 1){
                                                getCir3_1 = getCir3List.get(1);
                                            }
                                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                            String time = df.format(o.getUpdateTime());
                                            // 当前模式当前产品当前人的所有中条数
                                            List<CollageInRecord3> cir3List_1 = collageInRecord3Dao.queryCir3ByIds(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                            int cir3Size_1 = cir3List_1.size();
                                            List<CollageInRecord3> cir3List_1_1 = cir3List_1;
                                            boolean temp_1 = false;
                                            if(cir3Size_1 > 0){
                                                for(int h = 0; h < cir3Size_1; h++){
                                                    CollageInRecord3 cir3_1 = cir3List_1.get(h);
                                                    if(getCir3.getId() == cir3_1.getId()){

                                                        cir3_1.setStatus("1"); // 已返还
                                                        cir3_1.setEstimateReturn(time); // 当天返回一个代售

                                                        // 退钱
                                                        Account acc3 = accountDao.queryAccountByUserId(cir3_1.getUserId());
                                                        acc3.setVoucherBalance(acc3.getVoucherBalance().add(cir3_1.getPayAmount()));
                                                        accountDao.update(acc3);

                                                        AccountRecord ar = new AccountRecord();
                                                        ar.setIntoUserId(cir3_1.getUserId());
                                                        ar.setUpdateTime(new Date());
                                                        ar.setType("0");
                                                        ar.setAmount(cir3_1.getPayAmount());
                                                        ar.setNowAmount(acc3.getVoucherBalance());
                                                        ar.setSign("1");
                                                        ar.setOrderNo(o.getOrderNo());
                                                        // TODO 将12改成3
                                                        ar.setInfo(customerDao.queryById(cir3_1.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返回一个代售：" + cir3_1.getPayAmount());
                                                        accountRecordDao.save(ar);

                                                        // 修改订单信息
                                                        Orders orders1 = ordersDao.queryByOrderNo(cir3_1.getOrderNo());
                                                        if(orders1 != null){
                                                            orders1.setDealStatus("4"); // 交易关闭
                                                            orders1.setRefundStatus("2"); // 退款成功
                                                            orders1.setPayStatus("3"); // 已退款
                                                            ordersDao.update(orders1);
                                                        }

                                                        // 送共享券
                                                        UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir3_1.getUserId(), 2);
                                                        if(userCoupon != null){
                                                            userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                            userCoupon.setUpdateTime(new Date());
                                                            userCouponDao.update(userCoupon);

                                                            AccountRecord ar1 = new AccountRecord();
                                                            ar1.setIntoUserId(cir3_1.getUserId());
                                                            ar1.setUpdateTime(new Date());
                                                            ar1.setType("6");
                                                            ar1.setAmount(new BigDecimal(1));
                                                            ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                            ar1.setSign("1");
                                                            // TODO 将12改成3
                                                            ar1.setInfo(customerDao.queryById(cir3_1.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar1);
                                                        }else{
                                                            UserCoupon newUc = new UserCoupon();
                                                            newUc.setQuantity(1);
                                                            newUc.setUpdateTime(new Date());
                                                            newUc.setCouponId(2);
                                                            newUc.setUserId(cir3_1.getUserId());
                                                            userCouponDao.save(newUc);

                                                            AccountRecord ar2 = new AccountRecord();
                                                            ar2.setIntoUserId(cir3_1.getUserId());
                                                            ar2.setUpdateTime(new Date());
                                                            ar2.setType("6");
                                                            ar2.setAmount(new BigDecimal(1));
                                                            ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                            ar2.setSign("1");
                                                            // TODO 将12改成3
                                                            ar2.setInfo(customerDao.queryById(cir3_1.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar2);
                                                        }
                                                        List<CollageInRecord3> getCir3List_1 = collageInRecord3Dao.queryCir3ByIds_1_1(cir3_1.getModeId(), cir3_1.getProductId(), cir3_1.getUserId());
                                                        if(getCir3List_1.size() > 0){
                                                            temp_1 = false;
                                                            // 已经提过货了
                                                        }else{
                                                            temp_1 = true;
                                                            // 需要强制一个代售成为发货单
                                                        }
                                                    }
                                                    cir3_1.setIsTake("0"); // 不能提货
                                                    cir3_1.setEndTime(o.getUpdateTime()); // set第13个的时间
                                                    collageInRecord3Dao.update(cir3_1);

                                                }

                                                if(temp_1){
                                                    if(getCir3_1 != null){
                                                        for(int c = 0; c < cir3List_1_1.size(); c++){
                                                            CollageInRecord3 cir3_1_1 = cir3List_1_1.get(c);
                                                            if(getCir3_1.getId() == cir3_1_1.getId()) {
                                                                // 修改订单信息
                                                                Orders orders1_1_1 = ordersDao.queryByOrderNo(cir3_1_1.getOrderNo());
                                                                if(orders1_1_1 != null){
                                                                    orders1_1_1.setDealStatus("1"); // 待发货
                                                                    orders1_1_1.setRemarks("累计抽中已满三次, 当下返还一个代售并且再发货一个代售");
                                                                    ordersDao.update(orders1_1_1);

                                                                    cir3_1_1.setStatus("1"); // 已返还
                                                                    cir3_1_1.setEstimateReturn(time); // 当天返回一个代售
                                                                    collageInRecord3Dao.update(cir3_1_1);
                                                                }
                                                            }
                                                        }
                                                    }else{
                                                        System.err.println("没有代售了!!!");
                                                    }
                                                }

                                            }
                                        }

                                        // 将累计的总体修改为已退
                                        CollageInRecord3Copy isCir3Copy = collageInRecord3CopyDao.queryByIds(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                        if(isCir3Copy != null){
                                            isCir3Copy.setUpdateTime(new Date());
                                            isCir3Copy.setStatus("1");
                                            collageInRecord3CopyDao.update(isCir3Copy);
                                        }

                                        // 将剩余的代售进行定时，每月返回一个
                                        List<CollageInRecord3> cir3List_1 = collageInRecord3Dao.queryCir3ByIds_2(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                        int size = cir3List_1.size();
                                        if(size > 0){
                                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                            String time = df.format(o.getUpdateTime());
                                            TimeUtil timeUtil = new TimeUtil();
                                            String[] strings = timeUtil.getNextMonth_for(time, size);
                                            for(int z = 0; z < strings.length; z++){
                                                for(int x = 0; x < size; x++){
                                                    if(z == x){
                                                        CollageInRecord3 cir = cir3List_1.get(x);
                                                        cir.setEstimateReturn(strings[z]);
                                                        collageInRecord3Dao.update(cir);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }

                                // 速度与激情
                                if(orders.getCollageModeId() == 20){
                                    // 判断当前产品是否满六次，执行全额退款
                                    CollageInRecord20 cir20 = collageInRecord20Dao.queryCir20ByIds(orders.getCollageModeId(), orders.getOrderPersonId());
                                    if (cir20 == null) {
                                        // 第一次中当前产品
                                        CollageInRecord20 newCir20 = new CollageInRecord20();
                                        newCir20.setModeId(orders.getCollageModeId());
                                        newCir20.setUserId(orders.getOrderPersonId());
                                        newCir20.setStatus("0");
                                        newCir20.setTotalQuantity(1);
                                        newCir20.setPayAmount(orders.getPayAmount());
                                        newCir20.setUpdateTime(new Date());
                                        collageInRecord20Dao.save(newCir20);
                                    } else {
                                        // TODO 将6改成3
                                        if (cir20.getTotalQuantity() < 6) { // 调整为6
                                            // 继续累积
                                            cir20.setPayAmount(cir20.getPayAmount().add(orders.getPayAmount()));
                                            cir20.setTotalQuantity(cir20.getTotalQuantity() + 1);
                                            cir20.setUpdateTime(new Date());
                                            collageInRecord20Dao.update(cir20);
                                        } else {
                                            // 满足六次，退钱六次的钱
                                            cir20.setStatus("1");
                                            cir20.setUpdateTime(new Date());
                                            collageInRecord20Dao.update(cir20);

                                            Account accCir = accountDao.queryAccountByUserId(orders.getOrderPersonId());
                                            accCir.setVoucherBalance(accCir.getVoucherBalance().add(cir20.getPayAmount()));
                                            accountDao.update(accCir);

                                            AccountRecord arCir = new AccountRecord();
                                            arCir.setIntoUserId(orders.getOrderPersonId());
                                            arCir.setUpdateTime(new Date());
                                            arCir.setType("0");
                                            arCir.setAmount(cir20.getPayAmount());
                                            arCir.setNowAmount(accCir.getVoucherBalance());
                                            arCir.setSign("1");
                                            arCir.setOrderNo(orders.getOrderNo());
                                            // TODO 将6改成3
                                            arCir.setInfo(customer.getAgentCode() + "参团成功! 累积拼中产品六次,获得广告补贴为：" + cir20.getPayAmount());
                                            accountRecordDao.save(arCir);

                                            // 送共享券
                                            UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir20.getUserId(), 2);
                                            if (userCoupon != null) {
                                                userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                userCoupon.setUpdateTime(new Date());
                                                userCouponDao.update(userCoupon);

                                                AccountRecord ar1 = new AccountRecord();
                                                ar1.setIntoUserId(cir20.getUserId());
                                                ar1.setUpdateTime(new Date());
                                                ar1.setType("6");
                                                ar1.setAmount(new BigDecimal(1));
                                                ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                ar1.setSign("1");
                                                // TODO 将6改成3
                                                ar1.setInfo(customerDao.queryById(cir20.getUserId()).getAgentCode() + "参团成功! 累积拼中产品六次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar1);
                                            } else {
                                                UserCoupon newUc = new UserCoupon();
                                                newUc.setQuantity(1);
                                                newUc.setUpdateTime(new Date());
                                                newUc.setCouponId(2);
                                                newUc.setUserId(cir20.getUserId());
                                                userCouponDao.save(newUc);

                                                AccountRecord ar2 = new AccountRecord();
                                                ar2.setIntoUserId(cir20.getUserId());
                                                ar2.setUpdateTime(new Date());
                                                ar2.setType("6");
                                                ar2.setAmount(new BigDecimal(1));
                                                ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                ar2.setSign("1");
                                                // TODO 将6改成3
                                                ar2.setInfo(customerDao.queryById(cir20.getUserId()).getAgentCode() + "参团成功! 累积拼中产品六次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar2);
                                            }

                                            // 存下第七次
                                            CollageInRecord20 newCir7 = new CollageInRecord20();
                                            newCir7.setModeId(orders.getCollageModeId());
                                            newCir7.setUserId(orders.getOrderPersonId());
                                            newCir7.setStatus("0");
                                            newCir7.setTotalQuantity(1);
                                            newCir7.setPayAmount(orders.getPayAmount());
                                            newCir7.setUpdateTime(new Date());
                                            collageInRecord20Dao.save(newCir7);
                                        }
                                    }
                                }

                            }else{
                                // 是否退款
                                if("1".equals(o.getLastCollage())){

                                    // 当前订单转移到 OrdersCopy
                                    OrdersCopy oc = new OrdersCopy();
                                    oc.setId(o.getId());
                                    oc.setOrderNo(o.getOrderNo());
                                    oc.setTradeNo(o.getTradeNo());
                                    oc.setTotalAmount(o.getTotalAmount());
                                    oc.setFreight(o.getFreight());
                                    oc.setCollageModeId(o.getCollageModeId());
                                    oc.setOrderPersonId(o.getOrderPersonId());
                                    oc.setLastCollage(o.getLastCollage());
                                    oc.setConsigneeName(o.getConsigneeName());
                                    oc.setConsigneePhone(o.getConsigneePhone());
                                    oc.setAddress(o.getAddress());
                                    oc.setUpdateTime(new Date());
                                    oc.setPayAmount(o.getPayAmount());
                                    oc.setCouponAmount(o.getCouponAmount());
                                    oc.setModeProductId(o.getModeProductId());
                                    oc.setProductId(o.getProductId());
                                    oc.setCouponId(couponId);
                                    oc.setSkuId(orderDetailsDao.queryByOrderNo(o.getOrderNo()).getRelationId());
                                    BigDecimal couponAmount = null;
                                    if(o.getCouponAmount() == null){
                                        couponAmount = new BigDecimal(0);
                                    }else{
                                        couponAmount = o.getCouponAmount();
                                    }
                                    if(couponAmount.doubleValue() > 0){
                                        int quantity1 = (int) (couponAmount.doubleValue() / 9.9);
                                        oc.setCouponQuantity(quantity1);
                                    }else{
                                        oc.setCouponQuantity(0);
                                    }
                                    ordersCopyDao.save(oc);

                                    // 给个红包
//                                    Account accN = accountDao.queryAccountByUserId(o.getOrderPersonId());
//                                    Product p = productDao.queryById(o.getProductId());
//                                    accN.setVoucherBalance(accN.getVoucherBalance().add(p.getVoucher()));
//                                    accountDao.update(accN);
//
//                                    AccountRecord ar1_2 = new AccountRecord();
//                                    ar1_2.setIntoUserId(o.getOrderPersonId());
//                                    ar1_2.setUpdateTime(new Date());
//                                    ar1_2.setType("0");
//                                    ar1_2.setAmount(p.getVoucher());
//                                    ar1_2.setNowAmount(accN.getVoucherBalance());
//                                    ar1_2.setSign("1");
//                                    ar1_2.setOrderNo(o.getOrderNo());
//                                    ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + p.getVoucher());
//                                    accountRecordDao.save(ar1_2);

                                    FailRedPack frp = new FailRedPack();
                                    frp.setOrderNo(o.getOrderNo());
                                    frp.setPrizeMoney(product.getVoucher());
                                    frp.setStatus("2"); // 未开红包
                                    frp.setUpdateTime(new Date());
                                    frp.setUserId(o.getOrderPersonId());
                                    frp.setMode("0");
                                    failRedPackDao.save(frp);

                                    // 处理参与拼团后的利润分配
                                    // handleCollageProfit(o.getOrderPersonId(), p.getVoucher(), o.getOrderNo());

                                }else{
                                    // 执行退款(退到余额)退券 把每个人领取到的红包进行分润
                                    o.setDealStatus("4"); // 交易关闭
                                    o.setRefundStatus("2"); // 退款成功
                                    o.setPayStatus("3"); // 已退款
                                    ordersDao.update(o);

                                    Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                    acc.setVoucherBalance(acc.getVoucherBalance().add(o.getPayAmount()));
                                    accountDao.update(acc);

                                    AccountRecord ar1_1 = new AccountRecord();
                                    ar1_1.setIntoUserId(o.getOrderPersonId());
                                    ar1_1.setUpdateTime(new Date());
                                    ar1_1.setType("0");
                                    ar1_1.setAmount(o.getPayAmount());
                                    ar1_1.setNowAmount(acc.getVoucherBalance());
                                    ar1_1.setSign("1");
                                    ar1_1.setOrderNo(o.getOrderNo());
                                    ar1_1.setInfo(customer.getAgentCode() + "参团成功! 未抽中,支付金额退回至余额：" + o.getPayAmount());
                                    accountRecordDao.save(ar1_1);

                                    if(couponQuantity > 0){
                                        UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(o.getOrderPersonId(), couponId);
                                        if(uc != null){
                                            uc.setQuantity(uc.getQuantity() + couponQuantity);
                                            userCouponDao.update(uc);

                                            AccountRecord ar2 = new AccountRecord();
                                            ar2.setIntoUserId(o.getOrderPersonId());
                                            ar2.setUpdateTime(new Date());
                                            ar2.setType("5"); // 拼团券
                                            ar2.setAmount(new BigDecimal(couponQuantity));
                                            ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                                            ar2.setSign("1");
                                            ar2.setOrderNo(o.getOrderNo());
                                            ar2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,拼团券退回：" + couponQuantity);
                                            accountRecordDao.save(ar2);
                                        }
                                    }

                                    // acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher()));
                                    // accountDao.update(acc);

//                                    AccountRecord ar1_2 = new AccountRecord();
//                                    ar1_2.setIntoUserId(o.getOrderPersonId());
//                                    ar1_2.setUpdateTime(new Date());
//                                    ar1_2.setType("0");
//                                    ar1_2.setAmount(product.getVoucher());
//                                    ar1_2.setNowAmount(acc.getVoucherBalance());
//                                    ar1_2.setSign("1");
//                                    ar1_2.setOrderNo(o.getOrderNo());
//                                    ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + product.getVoucher());
//                                    accountRecordDao.save(ar1_2);

                                    FailRedPack frp = new FailRedPack();
                                    frp.setOrderNo(o.getOrderNo());
                                    frp.setPrizeMoney(product.getVoucher());
                                    frp.setStatus("2"); // 未开红包
                                    frp.setUpdateTime(new Date());
                                    frp.setUserId(o.getOrderPersonId());
                                    frp.setMode("0");
                                    failRedPackDao.save(frp);

                                    // 处理参与拼团后的利润分配
                                    // handleCollageProfit(userId, product.getVoucher(), orders.getOrderNo());

                                }
                            }
                        }
                    }
                }

            }else{
                // 糟糕

            }
        }
    }

    /**
     * 处理团
     * @param collageMode
     * @param product
     * @param userId
     * @param couponQuantity
     * @param skuId
     * @param couponId
     */
    @Override
    public void handleCollage_wx(Orders orders, CollageMode collageMode, Product product, Integer userId, Integer couponQuantity, Integer skuId,Integer couponId) throws ParseException {

        // 处理团信息
        ModeProduct modeProduct = modeProductDao.queryByProductIdByStatus(product.getId());
        if(modeProduct == null){
            // 创建新团
            ModeProduct newMP = new ModeProduct();
            newMP.setModeId(product.getCollageModeId());
            newMP.setProductId(product.getId());
            newMP.setStatus("0");
            newMP.setUpdateTime(new Date());
            modeProductDao.save(newMP);

            // 加入到当前团
            CollageUser newCU = new CollageUser();
            newCU.setModeProductId(newMP.getId());
            newCU.setUserId(userId);
            newCU.setUpdateTime(new Date());
            collageUserDao.save(newCU);

            // 修改订单的团ID
            orders.setModeProductId(newMP.getId());
            ordersDao.update(orders);

            System.err.println("修改订单成功 ------------------------------------------------------------- 范围：modeProduct == null");

        }else{
            int quantity = collageMode.getPeopleQuantity(); // 18 or 9 or 6
            // 查询现在这个产品团里面有多少人了
            List<CollageUser> collageUserList = collageUserDao.queryByModeProductId(modeProduct.getId());
            int rowSize = collageUserList.size(); // 已参与人数
            if(rowSize < (quantity -1)){

                // 直接加入
                CollageUser newCU = new CollageUser();
                newCU.setModeProductId(modeProduct.getId());
                newCU.setUserId(userId);
                newCU.setUpdateTime(new Date());
                collageUserDao.save(newCU);

                // 修改订单的团ID
                orders.setModeProductId(modeProduct.getId()); // set老团的ID
                ordersDao.update(orders);

                System.err.println("修改订单成功 ------------------------------------------------------------- 范围：rowSize < (quantity -1)");

            }else if(rowSize == (quantity -1)){ // 需要重新生成新团，并随机一个人中奖，其他人执行退款

                // 加入当前团
                CollageUser newCU = new CollageUser();
                newCU.setModeProductId(modeProduct.getId());
                newCU.setUserId(userId);
                newCU.setUpdateTime(new Date());
                collageUserDao.save(newCU);

                // 修改老团
                modeProduct.setStatus("1"); // 拼团成功
                if(modeProduct.getModeId() == 2){
                    // 极乐桑巴,时间判断
                    boolean temp = judgeCollageIsHandle();
                    if(temp){
                        // 正常流程执行
                    }else{
                        modeProduct.setIsWaitFor("1"); // 设为等待中
                    }
                }
                modeProductDao.update(modeProduct);

                // 修改订单的团ID
                ModeProduct newMo = new ModeProduct();
                newMo.setUpdateTime(new Date());
                newMo.setProductId(product.getId());
                newMo.setModeId(collageMode.getId());
                newMo.setStatus("0");
                modeProductDao.save(newMo);

                // 修改订单的团ID
                orders.setModeProductId(modeProduct.getId()); // set老团的ID
                ordersDao.update(orders);

                System.err.println("修改订单成功 ------------------------------------------------------------- 范围：rowSize == (quantity -1)");

                if(modeProduct.getModeId() == 2) {
                    // 极乐桑巴,时间判断
                    boolean temp = judgeCollageIsHandle();
                    if (temp) {
                        // 从老团中抽一个人中奖，其他人判断是否要进行自动退款
                        List<Orders> ordersList = ordersDao.queryOrdersByCollageProductId(modeProduct.getId());
                        int ordersSize = ordersList.size();
                        if(ordersSize > 0){
                            Random random = new Random();
                            int n = random.nextInt(ordersSize); // 随机抽中一条数据
                            for(int u = 0; u < ordersSize; u++){
                                Orders o = ordersList.get(u);
                                Customer customer = customerDao.queryById(o.getOrderPersonId());
                                if(u == n){
                                    // 添加销量
                                    product.setSales(product.getSales() + 1);
                                    productDao.update(product);

                                    // 中奖
                                    if(o.getCollageModeId() == 2){
                                        o.setDealStatus("1"); // 待发货
                                    }else if(o.getCollageModeId() == 3){
                                        o.setDealStatus("7"); // 代售
                                    }else if(o.getCollageModeId() == 4){
                                        o.setDealStatus("1"); // 待发货
                                    }else if(o.getCollageModeId() == 20){
                                        o.setDealStatus("1"); // 待发货
                                    }
                                    ordersDao.update(o);

                                    Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                    // 送3个极乐值
                                    acc.setBliss(acc.getBliss() + 3);
                                    // 送等额的积分
                                    int give = (int)Math.round(o.getPayAmount().doubleValue());
                                    acc.setIntegral(acc.getIntegral() + give);
                                    // 拼中也送红包余额
                                    acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher1()));
                                    accountDao.update(acc);

                                    AccountRecord ar3 = new AccountRecord();
                                    ar3.setIntoUserId(o.getOrderPersonId());
                                    ar3.setOrderNo(o.getOrderNo());
                                    ar3.setType("2");
                                    ar3.setSign("1");
                                    ar3.setUpdateTime(new Date());
                                    ar3.setAmount(new BigDecimal(3));
                                    ar3.setNowAmount(new BigDecimal(acc.getBliss()));
                                    ar3.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得极乐值：" + 3);
                                    accountRecordDao.save(ar3);

                                    AccountRecord ar3_1 = new AccountRecord();
                                    ar3_1.setIntoUserId(o.getOrderPersonId());
                                    ar3_1.setOrderNo(o.getOrderNo());
                                    ar3_1.setType("1");
                                    ar3_1.setSign("1");
                                    ar3_1.setUpdateTime(new Date());
                                    ar3_1.setAmount(new BigDecimal(give));
                                    ar3_1.setNowAmount(new BigDecimal(acc.getIntegral()));
                                    ar3_1.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得积分：" + give);
                                    accountRecordDao.save(ar3_1);

                                    AccountRecord ar3_2 = new AccountRecord();
                                    ar3_2.setIntoUserId(o.getOrderPersonId());
                                    ar3_2.setUpdateTime(new Date());
                                    ar3_2.setType("0");
                                    ar3_2.setAmount(product.getVoucher1());
                                    ar3_2.setNowAmount(acc.getVoucherBalance());
                                    ar3_2.setSign("1");
                                    ar3_2.setOrderNo(o.getOrderNo());
                                    ar3_2.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得红包余额：" + product.getVoucher1());
                                    accountRecordDao.save(ar3_2);

                                    // 处理参与拼团后的利润分配
                                    handleCollageProfit(o.getOrderPersonId(), product.getVoucher1(), orders.getOrderNo());

                                    // 极乐桑巴
                                    if(o.getCollageModeId() == 2){
                                        // 判断当前产品是否满六次，执行全额退款
                                        CollageInRecord2 cir2 = collageInRecord2Dao.queryCir2ByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                        if(cir2 == null){
                                            // 第一次中当前产品
                                            CollageInRecord2 newCir2 = new CollageInRecord2();
                                            newCir2.setModeId(o.getCollageModeId());
                                            newCir2.setProductId(o.getProductId());
                                            newCir2.setUserId(o.getOrderPersonId());
                                            newCir2.setStatus("0");
                                            newCir2.setTotalQuantity(1);
                                            newCir2.setPayAmount(o.getPayAmount());
                                            newCir2.setUpdateTime(new Date());
                                            collageInRecord2Dao.save(newCir2);
                                        }else{
                                            // TODO 将6改成3
                                            if(cir2.getTotalQuantity() < 3){
                                                // 继续累积
                                                cir2.setPayAmount(cir2.getPayAmount().add(o.getPayAmount()));
                                                cir2.setTotalQuantity(cir2.getTotalQuantity() + 1);
                                                cir2.setUpdateTime(new Date());
                                                collageInRecord2Dao.update(cir2);
                                            }else{
                                                // 满足六次，退钱六次的钱
                                                cir2.setStatus("1");
                                                cir2.setUpdateTime(new Date());
                                                collageInRecord2Dao.update(cir2);

                                                Account accCir = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                                accCir.setVoucherBalance(accCir.getVoucherBalance().add(cir2.getPayAmount()));
                                                accountDao.update(accCir);

                                                AccountRecord arCir = new AccountRecord();
                                                arCir.setIntoUserId(o.getOrderPersonId());
                                                arCir.setUpdateTime(new Date());
                                                arCir.setType("0");
                                                arCir.setAmount(cir2.getPayAmount());
                                                arCir.setNowAmount(accCir.getVoucherBalance());
                                                arCir.setSign("1");
                                                arCir.setOrderNo(o.getOrderNo());
                                                // TODO 将6改成3
                                                arCir.setInfo(customer.getAgentCode() + "参团成功! 累积拼中产品三次,获得广告补贴为：" + cir2.getPayAmount());
                                                accountRecordDao.save(arCir);

                                                // 送共享券
                                                UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir2.getUserId(), 2);
                                                if(userCoupon != null){
                                                    userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                    userCoupon.setUpdateTime(new Date());
                                                    userCouponDao.update(userCoupon);

                                                    AccountRecord ar1 = new AccountRecord();
                                                    ar1.setIntoUserId(cir2.getUserId());
                                                    ar1.setUpdateTime(new Date());
                                                    ar1.setType("6");
                                                    ar1.setAmount(new BigDecimal(1));
                                                    ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                    ar1.setSign("1");
                                                    // TODO 将6改成3
                                                    ar1.setInfo(customerDao.queryById(cir2.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                    accountRecordDao.save(ar1);
                                                }else{
                                                    UserCoupon newUc = new UserCoupon();
                                                    newUc.setQuantity(1);
                                                    newUc.setUpdateTime(new Date());
                                                    newUc.setCouponId(2);
                                                    newUc.setUserId(cir2.getUserId());
                                                    userCouponDao.save(newUc);

                                                    AccountRecord ar2 = new AccountRecord();
                                                    ar2.setIntoUserId(cir2.getUserId());
                                                    ar2.setUpdateTime(new Date());
                                                    ar2.setType("6");
                                                    ar2.setAmount(new BigDecimal(1));
                                                    ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                    ar2.setSign("1");
                                                    // TODO 将6改成3
                                                    ar2.setInfo(customerDao.queryById(cir2.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                    accountRecordDao.save(ar2);
                                                }

                                                // 存下第七次
                                                CollageInRecord2 newCir7 = new CollageInRecord2();
                                                newCir7.setModeId(o.getCollageModeId());
                                                newCir7.setProductId(o.getProductId());
                                                newCir7.setUserId(o.getOrderPersonId());
                                                newCir7.setStatus("0");
                                                newCir7.setTotalQuantity(1);
                                                newCir7.setPayAmount(o.getPayAmount());
                                                newCir7.setUpdateTime(new Date());
                                                collageInRecord2Dao.save(newCir7);
                                            }
                                        }

                                        // 判断当前拼团模式中是否存在满足六次的，有就执行退款
                                        // TODO 将6改成3
                                        CollageInRecord2 cir2_1 = collageInRecord2Dao.queryCir2ByIds_1(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                        if(cir2_1 != null){
                                            // 满足六次，退钱六次的钱
                                            cir2_1.setStatus("1");
                                            cir2_1.setUpdateTime(new Date());
                                            collageInRecord2Dao.update(cir2_1);

                                            Account accCir_1 = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                            accCir_1.setVoucherBalance(accCir_1.getVoucherBalance().add(cir2_1.getPayAmount()));
                                            accountDao.update(accCir_1);

                                            AccountRecord arCir_1 = new AccountRecord();
                                            arCir_1.setIntoUserId(o.getOrderPersonId());
                                            arCir_1.setUpdateTime(new Date());
                                            arCir_1.setType("0");
                                            arCir_1.setAmount(cir2_1.getPayAmount());
                                            arCir_1.setNowAmount(accCir_1.getVoucherBalance());
                                            arCir_1.setSign("1");
                                            arCir_1.setOrderNo(o.getOrderNo());
                                            // TODO 将6改成3
                                            arCir_1.setInfo(customer.getAgentCode() + "参团成功! 累积拼中产品三次,获得广告补贴为：" + cir2_1.getPayAmount());
                                            accountRecordDao.save(arCir_1);

                                            // 送共享券
                                            UserCoupon userCoupon1 = userCouponDao.queryByUserIdAndCouponId(cir2_1.getUserId(), 2);
                                            if(userCoupon1 != null){
                                                userCoupon1.setQuantity(userCoupon1.getQuantity() + 1);
                                                userCoupon1.setUpdateTime(new Date());
                                                userCouponDao.update(userCoupon1);

                                                AccountRecord ar1 = new AccountRecord();
                                                ar1.setIntoUserId(cir2_1.getUserId());
                                                ar1.setUpdateTime(new Date());
                                                ar1.setType("6");
                                                ar1.setAmount(new BigDecimal(1));
                                                ar1.setNowAmount(new BigDecimal(userCoupon1.getQuantity()));
                                                ar1.setSign("1");
                                                // TODO 将6改成3
                                                ar1.setInfo(customerDao.queryById(cir2_1.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar1);
                                            }else{
                                                UserCoupon newUc = new UserCoupon();
                                                newUc.setQuantity(1);
                                                newUc.setUpdateTime(new Date());
                                                newUc.setCouponId(2);
                                                newUc.setUserId(cir2_1.getUserId());
                                                userCouponDao.save(newUc);

                                                AccountRecord ar2 = new AccountRecord();
                                                ar2.setIntoUserId(cir2_1.getUserId());
                                                ar2.setUpdateTime(new Date());
                                                ar2.setType("6");
                                                ar2.setAmount(new BigDecimal(1));
                                                ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                ar2.setSign("1");
                                                // TODO 将6改成3
                                                ar2.setInfo(customerDao.queryById(cir2_1.getUserId()).getAgentCode() + "参团成功! 累积拼中产品三次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar2);
                                            }
                                        }

                                    }

                                }else{
                                    // 是否退款
                                    if("1".equals(o.getLastCollage())){

                                        // TODO 当前订单转移到 OrdersCopy
                                        OrdersCopy oc = new OrdersCopy();
                                        oc.setId(o.getId());
                                        oc.setOrderNo(o.getOrderNo());
                                        oc.setTradeNo(o.getTradeNo());
                                        oc.setTotalAmount(o.getTotalAmount());
                                        oc.setFreight(o.getFreight());
                                        oc.setCollageModeId(o.getCollageModeId());
                                        oc.setOrderPersonId(o.getOrderPersonId());
                                        oc.setLastCollage(o.getLastCollage());
                                        oc.setConsigneeName(o.getConsigneeName());
                                        oc.setConsigneePhone(o.getConsigneePhone());
                                        oc.setAddress(o.getAddress());
                                        oc.setUpdateTime(new Date());
                                        oc.setPayAmount(o.getPayAmount());
                                        oc.setCouponAmount(o.getCouponAmount());
                                        oc.setModeProductId(o.getModeProductId());
                                        oc.setProductId(o.getProductId());
                                        oc.setCouponId(couponId);
                                        oc.setSkuId(orderDetailsDao.queryByOrderNo(o.getOrderNo()).getRelationId());
                                        BigDecimal couponAmount = null;
                                        if(o.getCouponAmount() == null){
                                            couponAmount = new BigDecimal(0);
                                        }else{
                                            couponAmount = o.getCouponAmount();
                                        }
                                        if(couponAmount.doubleValue() > 0){
                                            int quantity1 = (int) (couponAmount.doubleValue() / 9.9);
                                            oc.setCouponQuantity(quantity1);
                                        }else{
                                            oc.setCouponQuantity(0);
                                        }
                                        ordersCopyDao.save(oc);

                                        // 给个红包
//                                        Account accN = accountDao.queryAccountByUserId(o.getOrderPersonId());
//                                        accN.setVoucherBalance(accN.getVoucherBalance().add(product.getVoucher()));
//                                        accountDao.update(accN);
//
//                                        AccountRecord ar1_2 = new AccountRecord();
//                                        ar1_2.setIntoUserId(o.getOrderPersonId());
//                                        ar1_2.setUpdateTime(new Date());
//                                        ar1_2.setType("0");
//                                        ar1_2.setAmount(product.getVoucher());
//                                        ar1_2.setNowAmount(accN.getVoucherBalance());
//                                        ar1_2.setSign("1");
//                                        ar1_2.setOrderNo(o.getOrderNo());
//                                        ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + product.getVoucher());
//                                        accountRecordDao.save(ar1_2);

                                        FailRedPack frp = new FailRedPack();
                                        frp.setOrderNo(o.getOrderNo());
                                        frp.setPrizeMoney(product.getVoucher());
                                        frp.setStatus("2"); // 未开红包
                                        frp.setUpdateTime(new Date());
                                        frp.setUserId(o.getOrderPersonId());
                                        frp.setMode("0");
                                        failRedPackDao.save(frp);

                                        // 处理参与拼团后的利润分配
                                        // handleCollageProfit(o.getOrderPersonId(), product.getVoucher(), o.getOrderNo());

                                    }else{
                                        // 执行退款(退到余额)退券 把每个人领取到的红包进行分润
                                        o.setDealStatus("4"); // 交易关闭
                                        o.setRefundStatus("2"); // 退款成功
                                        o.setPayStatus("3"); // 已退款
                                        ordersDao.update(o);

                                        Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                        acc.setVoucherBalance(acc.getVoucherBalance().add(o.getPayAmount()));
                                        accountDao.update(acc);

                                        AccountRecord ar1_1 = new AccountRecord();
                                        ar1_1.setIntoUserId(o.getOrderPersonId());
                                        ar1_1.setUpdateTime(new Date());
                                        ar1_1.setType("0");
                                        ar1_1.setAmount(o.getPayAmount());
                                        ar1_1.setNowAmount(acc.getVoucherBalance());
                                        ar1_1.setSign("1");
                                        ar1_1.setOrderNo(o.getOrderNo());
                                        ar1_1.setInfo(customer.getAgentCode() + "参团成功! 未抽中,支付金额退回至余额：" + o.getPayAmount());
                                        accountRecordDao.save(ar1_1);

                                        if(couponQuantity > 0){
                                            UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(o.getOrderPersonId(), couponId);
                                            if(uc != null){
                                                uc.setQuantity(uc.getQuantity() + couponQuantity);
                                                userCouponDao.update(uc);

                                                AccountRecord ar2 = new AccountRecord();
                                                ar2.setIntoUserId(o.getOrderPersonId());
                                                ar2.setUpdateTime(new Date());
                                                ar2.setType("5"); // 拼团券
                                                ar2.setAmount(new BigDecimal(couponQuantity));
                                                ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                                                ar2.setSign("1");
                                                ar2.setOrderNo(o.getOrderNo());
                                                ar2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,拼团券退回：" + couponQuantity);
                                                accountRecordDao.save(ar2);
                                            }
                                        }

                                        // acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher()));
                                        // accountDao.update(acc);

//                                        AccountRecord ar1_2 = new AccountRecord();
//                                        ar1_2.setIntoUserId(o.getOrderPersonId());
//                                        ar1_2.setUpdateTime(new Date());
//                                        ar1_2.setType("0");
//                                        ar1_2.setAmount(product.getVoucher());
//                                        ar1_2.setNowAmount(acc.getVoucherBalance());
//                                        ar1_2.setSign("1");
//                                        ar1_2.setOrderNo(o.getOrderNo());
//                                        ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + product.getVoucher());
//                                        accountRecordDao.save(ar1_2);

                                        FailRedPack frp = new FailRedPack();
                                        frp.setOrderNo(o.getOrderNo());
                                        frp.setPrizeMoney(product.getVoucher());
                                        frp.setStatus("2"); // 未开红包
                                        frp.setUpdateTime(new Date());
                                        frp.setUserId(o.getOrderPersonId());
                                        frp.setMode("0");
                                        failRedPackDao.save(frp);

                                        // 处理参与拼团后的利润分配
                                        // handleCollageProfit(o.getOrderPersonId(), product.getVoucher(), o.getOrderNo());

                                    }
                                }
                            }
                        }

                    } else {

                        // 极乐桑巴 每天 10:00-10:20    16:00-16:20    21:30-21:50  统一处理团

                    }
                }else{
                    // 从老团中抽一个人中奖，其他人判断是否要进行自动退款
                    List<Orders> ordersList = ordersDao.queryOrdersByCollageProductId(modeProduct.getId());
                    int ordersSize = ordersList.size();
                    if(ordersSize > 0){
                        Random random = new Random();
                        int n = random.nextInt(ordersSize); // 随机抽中一条数据
                        for(int u = 0; u < ordersSize; u++){
                            Orders o = ordersList.get(u);
                            Customer customer = customerDao.queryById(o.getOrderPersonId());
                            if(u == n){
                                // 添加销量
                                product.setSales(product.getSales() + 1);
                                productDao.update(product);

                                // 中奖
                                if(o.getCollageModeId() == 2){
                                    o.setDealStatus("1"); // 待发货
                                }else if(o.getCollageModeId() == 3){
                                    o.setDealStatus("7"); // 代售
                                }else if(o.getCollageModeId() == 4){
                                    o.setDealStatus("1"); // 待发货
                                }else if(o.getCollageModeId() == 20){
                                    o.setDealStatus("1"); // 待发货
                                }
                                ordersDao.update(o);

                                Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                // 送3个极乐值
                                acc.setBliss(acc.getBliss() + 3);
                                // 送等额的积分
                                int give = (int)Math.round(o.getPayAmount().doubleValue());
                                acc.setIntegral(acc.getIntegral() + give);
                                // 拼中也送红包余额
                                acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher1()));
                                accountDao.update(acc);

                                AccountRecord ar3 = new AccountRecord();
                                ar3.setIntoUserId(o.getOrderPersonId());
                                ar3.setOrderNo(o.getOrderNo());
                                ar3.setType("2");
                                ar3.setSign("1");
                                ar3.setUpdateTime(new Date());
                                ar3.setAmount(new BigDecimal(3));
                                ar3.setNowAmount(new BigDecimal(acc.getBliss()));
                                ar3.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得极乐值：" + 3);
                                accountRecordDao.save(ar3);

                                AccountRecord ar3_1 = new AccountRecord();
                                ar3_1.setIntoUserId(o.getOrderPersonId());
                                ar3_1.setOrderNo(o.getOrderNo());
                                ar3_1.setType("1");
                                ar3_1.setSign("1");
                                ar3_1.setUpdateTime(new Date());
                                ar3_1.setAmount(new BigDecimal(give));
                                ar3_1.setNowAmount(new BigDecimal(acc.getIntegral()));
                                ar3_1.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得积分：" + give);
                                accountRecordDao.save(ar3_1);

                                AccountRecord ar3_2 = new AccountRecord();
                                ar3_2.setIntoUserId(o.getOrderPersonId());
                                ar3_2.setUpdateTime(new Date());
                                ar3_2.setType("0");
                                ar3_2.setAmount(product.getVoucher1());
                                ar3_2.setNowAmount(acc.getVoucherBalance());
                                ar3_2.setSign("1");
                                ar3_2.setOrderNo(o.getOrderNo());
                                ar3_2.setInfo(customer.getAgentCode() + "参团成功! 拼中产品获得红包余额：" + product.getVoucher1());
                                accountRecordDao.save(ar3_2);

                                // 处理参与拼团后的利润分配
                                handleCollageProfit(o.getOrderPersonId(), product.getVoucher1(), orders.getOrderNo());

                                // 喜欢就拼
                                if(o.getCollageModeId() == 3){
                                    // 判断当前产品是否满十二次，执行每月代售
                                    // 查看当前模式当前产品当前人 一共中了多少条
                                    List<CollageInRecord3> cir3List = collageInRecord3Dao.queryCir3ByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                    List<CollageInRecord3> cir3List_copy = cir3List;
                                    int cir3Size = cir3List.size();
                                    if(cir3Size > 0){
                                        // TODO 将12改成3
                                        if(cir3Size < 3){
                                            // 未满十二次直接加一条
                                            CollageInRecord3 newCir3 = new CollageInRecord3();
                                            newCir3.setModeId(o.getCollageModeId());
                                            newCir3.setProductId(o.getProductId());
                                            newCir3.setUserId(o.getOrderPersonId());
                                            newCir3.setStatus("0"); // 未返还
                                            newCir3.setIsTake("1"); // 还能提货
                                            newCir3.setOrderNo(o.getOrderNo());
                                            newCir3.setPayAmount(o.getPayAmount());
                                            newCir3.setUpdateTime(o.getUpdateTime());
                                            collageInRecord3Dao.save(newCir3);

                                            // 查看CollageInRecord3Copy当前模式当前产品当前人一共累计有多少
                                            CollageInRecord3Copy cir3Copy = collageInRecord3CopyDao.queryByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            if(cir3Copy == null){
                                                // 创建并累计一次
                                                CollageInRecord3Copy newCir3Copy = new CollageInRecord3Copy();
                                                newCir3Copy.setModeId(o.getCollageModeId());
                                                newCir3Copy.setProductId(o.getProductId());
                                                newCir3Copy.setUserId(o.getOrderPersonId());
                                                newCir3Copy.setTotalQuantity(1);
                                                newCir3Copy.setStatus("0");
                                                newCir3Copy.setPayAmount(o.getPayAmount());
                                                newCir3Copy.setUpdateTime(new Date());
                                                collageInRecord3CopyDao.save(newCir3Copy);
                                            }else{
                                                // 直接累计一次
                                                cir3Copy.setTotalQuantity(cir3Copy.getTotalQuantity() + 1);
                                                cir3Copy.setPayAmount(cir3Copy.getPayAmount().add(o.getPayAmount()));
                                                cir3Copy.setUpdateTime(new Date());
                                                collageInRecord3CopyDao.update(cir3Copy);
                                            }

                                        }else{
                                            // 满足十二次了
                                            // 查看当前模式当前产品当前人下面有多少个代售 还没有返还能提货的条数
                                            List<CollageInRecord3> getCir3List = collageInRecord3Dao.queryCir3ByIds_1(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            if(getCir3List.size() > 0){
                                                CollageInRecord3 getCir3 = getCir3List.get(0);
                                                CollageInRecord3 getCir3_1 = null;
                                                if(getCir3List.size() > 1){
                                                    getCir3_1 = getCir3List.get(1);
                                                }
                                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                                String time = df.format(o.getUpdateTime());
                                                boolean temp = false;
                                                for(int v = 0; v < cir3Size; v++){
                                                    CollageInRecord3 cir3 = cir3List.get(v);
                                                    if(getCir3.getId() == cir3.getId()){ // 未返并能提货中的第一个去匹配所有的得到一条数据进行代售

                                                        cir3.setStatus("1"); // 已返还
                                                        cir3.setEstimateReturn(time); // 当天返回一个代售   yyyy-MM-dd  时间为当下返回的代售标记

                                                        // 退钱
                                                        Account acc3 = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                                        acc3.setVoucherBalance(acc3.getVoucherBalance().add(cir3.getPayAmount()));
                                                        accountDao.update(acc3);

                                                        AccountRecord ar = new AccountRecord();
                                                        ar.setIntoUserId(o.getOrderPersonId());
                                                        ar.setUpdateTime(new Date());
                                                        ar.setType("0");
                                                        ar.setAmount(cir3.getPayAmount());
                                                        ar.setNowAmount(acc3.getVoucherBalance());
                                                        ar.setSign("1");
                                                        ar.setOrderNo(o.getOrderNo());
                                                        // TODO 将12改成3
                                                        ar.setInfo(customer.getAgentCode() + "参团成功! 累计抽中已满三次, 当下返回一个代售：" + cir3.getPayAmount());
                                                        accountRecordDao.save(ar);

                                                        // 修改订单信息
                                                        Orders orders1 = ordersDao.queryByOrderNo(cir3.getOrderNo());
                                                        if(orders1 != null){
                                                            orders1.setDealStatus("4"); // 交易关闭
                                                            orders1.setRefundStatus("2"); // 退款成功
                                                            orders1.setPayStatus("3"); // 已退款
                                                            ordersDao.update(orders1);
                                                        }

                                                        // 送共享券
                                                        UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir3.getUserId(), 2); // 2 是共享券
                                                        if(userCoupon != null){
                                                            userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                            userCoupon.setUpdateTime(new Date());
                                                            userCouponDao.update(userCoupon);

                                                            AccountRecord ar1 = new AccountRecord();
                                                            ar1.setIntoUserId(cir3.getUserId());
                                                            ar1.setUpdateTime(new Date());
                                                            ar1.setType("6");
                                                            ar1.setAmount(new BigDecimal(1));
                                                            ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                            ar1.setSign("1");
                                                            // TODO 将12改成3
                                                            ar1.setInfo(customerDao.queryById(cir3.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar1);
                                                        }else{
                                                            UserCoupon newUc = new UserCoupon();
                                                            newUc.setQuantity(1);
                                                            newUc.setUpdateTime(new Date());
                                                            newUc.setCouponId(2);
                                                            newUc.setUserId(cir3.getUserId());
                                                            userCouponDao.save(newUc);

                                                            AccountRecord ar2 = new AccountRecord();
                                                            ar2.setIntoUserId(cir3.getUserId());
                                                            ar2.setUpdateTime(new Date());
                                                            ar2.setType("6");
                                                            ar2.setAmount(new BigDecimal(1));
                                                            ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                            ar2.setSign("1");
                                                            // TODO 将12改成3
                                                            ar2.setInfo(customerDao.queryById(cir3.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar2);
                                                        }

                                                        // 查看当前模式当前产品当前人 是否 我要自提过
                                                        List<CollageInRecord3> getCir3List_1 = collageInRecord3Dao.queryCir3ByIds_1_1(cir3.getModeId(), cir3.getProductId(), cir3.getUserId());
                                                        if(getCir3List_1.size() > 0){
                                                            temp = false;
                                                            // 已经提过货了
                                                        }else{
                                                            temp = true;
                                                            // 需要强制一个代售成为发货单
                                                        }

                                                    }
                                                    cir3.setIsTake("0"); // 不能提货
                                                    cir3.setEndTime(o.getUpdateTime()); // set第13个的时间
                                                    collageInRecord3Dao.update(cir3);
                                                }

                                                if(temp){
                                                    if(getCir3_1 != null){
                                                        for(int b = 0; b < cir3List_copy.size(); b++){
                                                            CollageInRecord3 cir3_1 = cir3List_copy.get(b);
                                                            if(getCir3_1.getId() == cir3_1.getId()) {
                                                                // 修改订单信息
                                                                Orders orders1_1 = ordersDao.queryByOrderNo(cir3_1.getOrderNo());
                                                                if(orders1_1 != null){
                                                                    orders1_1.setDealStatus("1"); // 待发货
                                                                    orders1_1.setRemarks("累计抽中已满三次, 当下返还一个代售并且再发货一个代售");
                                                                    ordersDao.update(orders1_1);

                                                                    cir3_1.setStatus("1"); // 已返还
                                                                    cir3_1.setEstimateReturn(time); // 当天再返回一个代售
                                                                    collageInRecord3Dao.update(cir3_1);
                                                                }
                                                            }
                                                        }
                                                    }else{
                                                        System.err.println("没有代售了!!!");
                                                    }
                                                }

                                            }

                                            // 将累计的总体修改为已退
                                            CollageInRecord3Copy isCir3Copy = collageInRecord3CopyDao.queryByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            if(isCir3Copy != null){
                                                isCir3Copy.setUpdateTime(new Date());
                                                isCir3Copy.setStatus("1");
                                                collageInRecord3CopyDao.update(isCir3Copy);
                                            }

                                            // 将剩余的代售进行定时，每月返回一个
                                            List<CollageInRecord3> cir3List_1 = collageInRecord3Dao.queryCir3ByIds_2(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                            int size = cir3List_1.size();
                                            if(size > 0){
                                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                                String time = df.format(o.getUpdateTime());
                                                TimeUtil timeUtil = new TimeUtil();
                                                String[] strings = timeUtil.getNextMonth_for(time, size);
                                                for(int z = 0; z < strings.length; z++){
                                                    for(int x = 0; x < size; x++){
                                                        if(z == x){
                                                            CollageInRecord3 cir = cir3List_1.get(x);
                                                            cir.setEstimateReturn(strings[z]);
                                                            collageInRecord3Dao.update(cir);
                                                        }
                                                    }
                                                }
                                            }

                                            // 创建第13个
                                            CollageInRecord3 newCir3 = new CollageInRecord3();
                                            newCir3.setModeId(o.getCollageModeId());
                                            newCir3.setProductId(o.getProductId());
                                            newCir3.setUserId(o.getOrderPersonId());
                                            newCir3.setStatus("0");
                                            newCir3.setIsTake("1");
                                            newCir3.setOrderNo(o.getOrderNo());
                                            newCir3.setPayAmount(o.getPayAmount());
                                            newCir3.setUpdateTime(o.getUpdateTime());
                                            collageInRecord3Dao.save(newCir3);

                                        }

                                    }else{
                                        // 第一次拼中当前产品
                                        CollageInRecord3 newCir4 = new CollageInRecord3();
                                        newCir4.setModeId(o.getCollageModeId());
                                        newCir4.setProductId(o.getProductId());
                                        newCir4.setUserId(o.getOrderPersonId());
                                        newCir4.setStatus("0"); // 未返还
                                        newCir4.setIsTake("1"); // 还能提货
                                        newCir4.setOrderNo(o.getOrderNo());
                                        newCir4.setPayAmount(o.getPayAmount());
                                        newCir4.setUpdateTime(o.getUpdateTime());
                                        collageInRecord3Dao.save(newCir4);

                                        // 查看CollageInRecord3Copy当前模式当前产品当前人一共累计有多少
                                        CollageInRecord3Copy cir3Copy = collageInRecord3CopyDao.queryByIds(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                        if(cir3Copy == null){
                                            // 创建并累计一次
                                            CollageInRecord3Copy newCir3Copy = new CollageInRecord3Copy();
                                            newCir3Copy.setModeId(o.getCollageModeId());
                                            newCir3Copy.setProductId(o.getProductId());
                                            newCir3Copy.setUserId(o.getOrderPersonId());
                                            newCir3Copy.setTotalQuantity(1);
                                            newCir3Copy.setStatus("0");
                                            newCir3Copy.setPayAmount(o.getPayAmount());
                                            newCir3Copy.setUpdateTime(new Date());
                                            collageInRecord3CopyDao.save(newCir3Copy);
                                        }else{
                                            // 直接累计一次
                                            cir3Copy.setTotalQuantity(cir3Copy.getTotalQuantity() + 1);
                                            cir3Copy.setPayAmount(cir3Copy.getPayAmount().add(o.getPayAmount()));
                                            cir3Copy.setUpdateTime(new Date());
                                            collageInRecord3CopyDao.update(cir3Copy);
                                        }
                                    }


                                    // TODO 判断当前拼团模式中是否存在满足十二次的 // TODO 将12改成3
                                    CollageInRecord3Copy cir3Copy12 = collageInRecord3CopyDao.queryByIds_1(o.getCollageModeId(), o.getProductId(), o.getOrderPersonId());
                                    if(cir3Copy12 != null){
                                        // 满足十二次了
                                        List<CollageInRecord3> getCir3List = collageInRecord3Dao.queryCir3ByIds_1(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                        if(getCir3List.size() > 0){
                                            CollageInRecord3 getCir3 = getCir3List.get(0);
                                            CollageInRecord3 getCir3_1 = null;
                                            if(getCir3List.size() > 1){
                                                getCir3_1 = getCir3List.get(1);
                                            }
                                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                            String time = df.format(o.getUpdateTime());
                                            // 当前模式当前产品当前人的所有中条数
                                            List<CollageInRecord3> cir3List_1 = collageInRecord3Dao.queryCir3ByIds(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                            int cir3Size_1 = cir3List_1.size();
                                            List<CollageInRecord3> cir3List_1_1 = cir3List_1;
                                            boolean temp_1 = false;
                                            if(cir3Size_1 > 0){
                                                for(int h = 0; h < cir3Size_1; h++){
                                                    CollageInRecord3 cir3_1 = cir3List_1.get(h);
                                                    if(getCir3.getId() == cir3_1.getId()){

                                                        cir3_1.setStatus("1"); // 已返还
                                                        cir3_1.setEstimateReturn(time); // 当天返回一个代售

                                                        // 退钱
                                                        Account acc3 = accountDao.queryAccountByUserId(cir3_1.getUserId());
                                                        acc3.setVoucherBalance(acc3.getVoucherBalance().add(cir3_1.getPayAmount()));
                                                        accountDao.update(acc3);

                                                        AccountRecord ar = new AccountRecord();
                                                        ar.setIntoUserId(cir3_1.getUserId());
                                                        ar.setUpdateTime(new Date());
                                                        ar.setType("0");
                                                        ar.setAmount(cir3_1.getPayAmount());
                                                        ar.setNowAmount(acc3.getVoucherBalance());
                                                        ar.setSign("1");
                                                        ar.setOrderNo(o.getOrderNo());
                                                        // TODO 将12改成3
                                                        ar.setInfo(customerDao.queryById(cir3_1.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返回一个代售：" + cir3_1.getPayAmount());
                                                        accountRecordDao.save(ar);

                                                        // 修改订单信息
                                                        Orders orders1 = ordersDao.queryByOrderNo(cir3_1.getOrderNo());
                                                        if(orders1 != null){
                                                            orders1.setDealStatus("4"); // 交易关闭
                                                            orders1.setRefundStatus("2"); // 退款成功
                                                            orders1.setPayStatus("3"); // 已退款
                                                            ordersDao.update(orders1);
                                                        }

                                                        // 送共享券
                                                        UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir3_1.getUserId(), 2);
                                                        if(userCoupon != null){
                                                            userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                            userCoupon.setUpdateTime(new Date());
                                                            userCouponDao.update(userCoupon);

                                                            AccountRecord ar1 = new AccountRecord();
                                                            ar1.setIntoUserId(cir3_1.getUserId());
                                                            ar1.setUpdateTime(new Date());
                                                            ar1.setType("6");
                                                            ar1.setAmount(new BigDecimal(1));
                                                            ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                            ar1.setSign("1");
                                                            // TODO 将12改成3
                                                            ar1.setInfo(customerDao.queryById(cir3_1.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar1);
                                                        }else{
                                                            UserCoupon newUc = new UserCoupon();
                                                            newUc.setQuantity(1);
                                                            newUc.setUpdateTime(new Date());
                                                            newUc.setCouponId(2);
                                                            newUc.setUserId(cir3_1.getUserId());
                                                            userCouponDao.save(newUc);

                                                            AccountRecord ar2 = new AccountRecord();
                                                            ar2.setIntoUserId(cir3_1.getUserId());
                                                            ar2.setUpdateTime(new Date());
                                                            ar2.setType("6");
                                                            ar2.setAmount(new BigDecimal(1));
                                                            ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                            ar2.setSign("1");
                                                            // TODO 将12改成3
                                                            ar2.setInfo(customerDao.queryById(cir3_1.getUserId()).getAgentCode() + "参团成功! 累计抽中已满三次, 当下返还代售时赠送共享券：" + 1);
                                                            accountRecordDao.save(ar2);
                                                        }
                                                        List<CollageInRecord3> getCir3List_1 = collageInRecord3Dao.queryCir3ByIds_1_1(cir3_1.getModeId(), cir3_1.getProductId(), cir3_1.getUserId());
                                                        if(getCir3List_1.size() > 0){
                                                            temp_1 = false;
                                                            // 已经提过货了
                                                        }else{
                                                            temp_1 = true;
                                                            // 需要强制一个代售成为发货单
                                                        }
                                                    }
                                                    cir3_1.setIsTake("0"); // 不能提货
                                                    cir3_1.setEndTime(o.getUpdateTime()); // set第13个的时间
                                                    collageInRecord3Dao.update(cir3_1);

                                                }

                                                if(temp_1){
                                                    if(getCir3_1 != null){
                                                        for(int c = 0; c < cir3List_1_1.size(); c++){
                                                            CollageInRecord3 cir3_1_1 = cir3List_1_1.get(c);
                                                            if(getCir3_1.getId() == cir3_1_1.getId()) {
                                                                // 修改订单信息
                                                                Orders orders1_1_1 = ordersDao.queryByOrderNo(cir3_1_1.getOrderNo());
                                                                if(orders1_1_1 != null){
                                                                    orders1_1_1.setDealStatus("1"); // 待发货
                                                                    orders1_1_1.setRemarks("累计抽中已满三次, 当下返还一个代售并且再发货一个代售");
                                                                    ordersDao.update(orders1_1_1);

                                                                    cir3_1_1.setStatus("1"); // 已返还
                                                                    cir3_1_1.setEstimateReturn(time); // 当天返回一个代售
                                                                    collageInRecord3Dao.update(cir3_1_1);
                                                                }
                                                            }
                                                        }
                                                    }else{
                                                        System.err.println("没有代售了!!!");
                                                    }
                                                }

                                            }
                                        }

                                        // 将累计的总体修改为已退
                                        CollageInRecord3Copy isCir3Copy = collageInRecord3CopyDao.queryByIds(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                        if(isCir3Copy != null){
                                            isCir3Copy.setUpdateTime(new Date());
                                            isCir3Copy.setStatus("1");
                                            collageInRecord3CopyDao.update(isCir3Copy);
                                        }

                                        // 将剩余的代售进行定时，每月返回一个
                                        List<CollageInRecord3> cir3List_1 = collageInRecord3Dao.queryCir3ByIds_2(cir3Copy12.getModeId(), cir3Copy12.getProductId(), cir3Copy12.getUserId());
                                        int size = cir3List_1.size();
                                        if(size > 0){
                                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                            String time = df.format(o.getUpdateTime());
                                            TimeUtil timeUtil = new TimeUtil();
                                            String[] strings = timeUtil.getNextMonth_for(time, size);
                                            for(int z = 0; z < strings.length; z++){
                                                for(int x = 0; x < size; x++){
                                                    if(z == x){
                                                        CollageInRecord3 cir = cir3List_1.get(x);
                                                        cir.setEstimateReturn(strings[z]);
                                                        collageInRecord3Dao.update(cir);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }

                                // 速度与激情
                                if(orders.getCollageModeId() == 20){
                                    // 判断当前产品是否满六次，执行全额退款
                                    CollageInRecord20 cir20 = collageInRecord20Dao.queryCir20ByIds(orders.getCollageModeId(), orders.getOrderPersonId());
                                    if (cir20 == null) {
                                        // 第一次中当前产品
                                        CollageInRecord20 newCir20 = new CollageInRecord20();
                                        newCir20.setModeId(orders.getCollageModeId());
                                        newCir20.setUserId(orders.getOrderPersonId());
                                        newCir20.setStatus("0");
                                        newCir20.setTotalQuantity(1);
                                        newCir20.setPayAmount(orders.getPayAmount());
                                        newCir20.setUpdateTime(new Date());
                                        collageInRecord20Dao.save(newCir20);
                                    } else {
                                        // TODO 将6改成3
                                        if (cir20.getTotalQuantity() < 6) { // 调整为6
                                            // 继续累积
                                            cir20.setPayAmount(cir20.getPayAmount().add(orders.getPayAmount()));
                                            cir20.setTotalQuantity(cir20.getTotalQuantity() + 1);
                                            cir20.setUpdateTime(new Date());
                                            collageInRecord20Dao.update(cir20);
                                        } else {
                                            // 满足六次，退钱六次的钱
                                            cir20.setStatus("1");
                                            cir20.setUpdateTime(new Date());
                                            collageInRecord20Dao.update(cir20);

                                            Account accCir = accountDao.queryAccountByUserId(orders.getOrderPersonId());
                                            accCir.setVoucherBalance(accCir.getVoucherBalance().add(cir20.getPayAmount()));
                                            accountDao.update(accCir);

                                            AccountRecord arCir = new AccountRecord();
                                            arCir.setIntoUserId(orders.getOrderPersonId());
                                            arCir.setUpdateTime(new Date());
                                            arCir.setType("0");
                                            arCir.setAmount(cir20.getPayAmount());
                                            arCir.setNowAmount(accCir.getVoucherBalance());
                                            arCir.setSign("1");
                                            arCir.setOrderNo(orders.getOrderNo());
                                            // TODO 将6改成3
                                            arCir.setInfo(customer.getAgentCode() + "参团成功! 累积拼中产品六次,获得广告补贴为：" + cir20.getPayAmount());
                                            accountRecordDao.save(arCir);

                                            // 送共享券
                                            UserCoupon userCoupon = userCouponDao.queryByUserIdAndCouponId(cir20.getUserId(), 2);
                                            if (userCoupon != null) {
                                                userCoupon.setQuantity(userCoupon.getQuantity() + 1);
                                                userCoupon.setUpdateTime(new Date());
                                                userCouponDao.update(userCoupon);

                                                AccountRecord ar1 = new AccountRecord();
                                                ar1.setIntoUserId(cir20.getUserId());
                                                ar1.setUpdateTime(new Date());
                                                ar1.setType("6");
                                                ar1.setAmount(new BigDecimal(1));
                                                ar1.setNowAmount(new BigDecimal(userCoupon.getQuantity()));
                                                ar1.setSign("1");
                                                // TODO 将6改成3
                                                ar1.setInfo(customerDao.queryById(cir20.getUserId()).getAgentCode() + "参团成功! 累积拼中产品六次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar1);
                                            } else {
                                                UserCoupon newUc = new UserCoupon();
                                                newUc.setQuantity(1);
                                                newUc.setUpdateTime(new Date());
                                                newUc.setCouponId(2);
                                                newUc.setUserId(cir20.getUserId());
                                                userCouponDao.save(newUc);

                                                AccountRecord ar2 = new AccountRecord();
                                                ar2.setIntoUserId(cir20.getUserId());
                                                ar2.setUpdateTime(new Date());
                                                ar2.setType("6");
                                                ar2.setAmount(new BigDecimal(1));
                                                ar2.setNowAmount(new BigDecimal(newUc.getQuantity()));
                                                ar2.setSign("1");
                                                // TODO 将6改成3
                                                ar2.setInfo(customerDao.queryById(cir20.getUserId()).getAgentCode() + "参团成功! 累积拼中产品六次,退款总金额并赠送共享券：" + 1);
                                                accountRecordDao.save(ar2);
                                            }

                                            // 存下第七次
                                            CollageInRecord20 newCir7 = new CollageInRecord20();
                                            newCir7.setModeId(orders.getCollageModeId());
                                            newCir7.setUserId(orders.getOrderPersonId());
                                            newCir7.setStatus("0");
                                            newCir7.setTotalQuantity(1);
                                            newCir7.setPayAmount(orders.getPayAmount());
                                            newCir7.setUpdateTime(new Date());
                                            collageInRecord20Dao.save(newCir7);
                                        }
                                    }
                                }

                            }else{
                                // 是否退款
                                if("1".equals(o.getLastCollage())){

                                    // 当前订单转移到 OrdersCopy
                                    OrdersCopy oc = new OrdersCopy();
                                    oc.setId(o.getId());
                                    oc.setOrderNo(o.getOrderNo());
                                    oc.setTradeNo(o.getTradeNo());
                                    oc.setTotalAmount(o.getTotalAmount());
                                    oc.setFreight(o.getFreight());
                                    oc.setCollageModeId(o.getCollageModeId());
                                    oc.setOrderPersonId(o.getOrderPersonId());
                                    oc.setLastCollage(o.getLastCollage());
                                    oc.setConsigneeName(o.getConsigneeName());
                                    oc.setConsigneePhone(o.getConsigneePhone());
                                    oc.setAddress(o.getAddress());
                                    oc.setUpdateTime(new Date());
                                    oc.setPayAmount(o.getPayAmount());
                                    oc.setCouponAmount(o.getCouponAmount());
                                    oc.setModeProductId(o.getModeProductId());
                                    oc.setProductId(o.getProductId());
                                    oc.setCouponId(couponId);
                                    oc.setSkuId(orderDetailsDao.queryByOrderNo(o.getOrderNo()).getRelationId());
                                    BigDecimal couponAmount = null;
                                    if(o.getCouponAmount() == null){
                                        couponAmount = new BigDecimal(0);
                                    }else{
                                        couponAmount = o.getCouponAmount();
                                    }
                                    if(couponAmount.doubleValue() > 0){
                                        int quantity1 = (int) (couponAmount.doubleValue() / 9.9);
                                        oc.setCouponQuantity(quantity1);
                                    }else{
                                        oc.setCouponQuantity(0);
                                    }
                                    ordersCopyDao.save(oc);

                                    // 给个红包
//                                    Account accN = accountDao.queryAccountByUserId(o.getOrderPersonId());
//                                    accN.setVoucherBalance(accN.getVoucherBalance().add(product.getVoucher()));
//                                    accountDao.update(accN);
//
//                                    AccountRecord ar1_2 = new AccountRecord();
//                                    ar1_2.setIntoUserId(o.getOrderPersonId());
//                                    ar1_2.setUpdateTime(new Date());
//                                    ar1_2.setType("0");
//                                    ar1_2.setAmount(product.getVoucher());
//                                    ar1_2.setNowAmount(accN.getVoucherBalance());
//                                    ar1_2.setSign("1");
//                                    ar1_2.setOrderNo(o.getOrderNo());
//                                    ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + product.getVoucher());
//                                    accountRecordDao.save(ar1_2);

                                    FailRedPack frp = new FailRedPack();
                                    frp.setOrderNo(o.getOrderNo());
                                    frp.setPrizeMoney(product.getVoucher());
                                    frp.setStatus("2"); // 未开红包
                                    frp.setUpdateTime(new Date());
                                    frp.setUserId(o.getOrderPersonId());
                                    frp.setMode("0");
                                    failRedPackDao.save(frp);

                                    // 处理参与拼团后的利润分配
                                    // handleCollageProfit(o.getOrderPersonId(), product.getVoucher(), o.getOrderNo());

                                }else{
                                    // 执行退款(退到余额)退券 把每个人领取到的红包进行分润
                                    o.setDealStatus("4"); // 交易关闭
                                    o.setRefundStatus("2"); // 退款成功
                                    o.setPayStatus("3"); // 已退款
                                    ordersDao.update(o);

                                    Account acc = accountDao.queryAccountByUserId(o.getOrderPersonId());
                                    acc.setVoucherBalance(acc.getVoucherBalance().add(o.getPayAmount()));
                                    accountDao.update(acc);

                                    AccountRecord ar1_1 = new AccountRecord();
                                    ar1_1.setIntoUserId(o.getOrderPersonId());
                                    ar1_1.setUpdateTime(new Date());
                                    ar1_1.setType("0");
                                    ar1_1.setAmount(o.getPayAmount());
                                    ar1_1.setNowAmount(acc.getVoucherBalance());
                                    ar1_1.setSign("1");
                                    ar1_1.setOrderNo(o.getOrderNo());
                                    ar1_1.setInfo(customer.getAgentCode() + "参团成功! 未抽中,支付金额退回至余额：" + o.getPayAmount());
                                    accountRecordDao.save(ar1_1);

                                    if(couponQuantity > 0){
                                        UserCoupon uc = userCouponDao.queryByUserIdAndCouponId(o.getOrderPersonId(), couponId);
                                        if(uc != null){
                                            uc.setQuantity(uc.getQuantity() + couponQuantity);
                                            userCouponDao.update(uc);

                                            AccountRecord ar2 = new AccountRecord();
                                            ar2.setIntoUserId(o.getOrderPersonId());
                                            ar2.setUpdateTime(new Date());
                                            ar2.setType("5"); // 拼团券
                                            ar2.setAmount(new BigDecimal(couponQuantity));
                                            ar2.setNowAmount(new BigDecimal(uc.getQuantity()));
                                            ar2.setSign("1");
                                            ar2.setOrderNo(o.getOrderNo());
                                            ar2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,拼团券退回：" + couponQuantity);
                                            accountRecordDao.save(ar2);
                                        }
                                    }

                                    // acc.setVoucherBalance(acc.getVoucherBalance().add(product.getVoucher()));
                                    // accountDao.update(acc);

//                                    AccountRecord ar1_2 = new AccountRecord();
//                                    ar1_2.setIntoUserId(o.getOrderPersonId());
//                                    ar1_2.setUpdateTime(new Date());
//                                    ar1_2.setType("0");
//                                    ar1_2.setAmount(product.getVoucher());
//                                    ar1_2.setNowAmount(acc.getVoucherBalance());
//                                    ar1_2.setSign("1");
//                                    ar1_2.setOrderNo(o.getOrderNo());
//                                    ar1_2.setInfo(customer.getAgentCode() + "参团成功! 未抽中,送您余额：" + product.getVoucher());
//                                    accountRecordDao.save(ar1_2);

                                    FailRedPack frp = new FailRedPack();
                                    frp.setOrderNo(o.getOrderNo());
                                    frp.setPrizeMoney(product.getVoucher());
                                    frp.setStatus("2"); // 未开红包
                                    frp.setUpdateTime(new Date());
                                    frp.setUserId(o.getOrderPersonId());
                                    frp.setMode("0");
                                    failRedPackDao.save(frp);

                                    // 处理参与拼团后的利润分配
                                    // handleCollageProfit(o.getOrderPersonId(), product.getVoucher(), o.getOrderNo());

                                }
                            }
                        }
                    }
                }

            }else{
                // 糟糕
            }
        }
    }

    @Override
    public void handleCollageProfit(Integer userId, BigDecimal voucherBalance, String orderNo) {
        Customer customer = customerDao.queryById(userId);
        if(customer != null){

            BigDecimal bigDecimal5 = new BigDecimal(0.05);
            BigDecimal bigDecimal10 = new BigDecimal(0.1);
            BigDecimal bigDecimal15 = new BigDecimal(0.15);
            BigDecimal bigDecimal20 = new BigDecimal(0.2);
            BigDecimal bigDecimal25 = new BigDecimal(0.25);

            BigDecimal bigDecimal3 = new BigDecimal(0.03);
            BigDecimal bigDecimal6 = new BigDecimal(0.06);
            BigDecimal bigDecimal9 = new BigDecimal(0.09);
            BigDecimal bigDecimal12 = new BigDecimal(0.12);
            BigDecimal bigDecimal15_2 = new BigDecimal(0.15);

            BigDecimal bigDecimal1 = new BigDecimal(0.01);

            //第一层
            if(customer.getParentId() != null && customer.getParentId() != 1198 && customer.getLevelId() != 7){
                Customer parentCustomer = customerDao.queryById(customer.getParentId());
                if(parentCustomer != null){
                    if(parentCustomer.getLevelId() == 1 && "1".equals(parentCustomer.getIsActive())){

                    }else if(parentCustomer.getLevelId() == 2 && "1".equals(parentCustomer.getIsActive())){

                        String str = "5%";
                        shareProfitRecord(customer, parentCustomer.getId(), voucherBalance, bigDecimal5, orderNo, str);

                    }else if(parentCustomer.getLevelId() == 3 && "1".equals(parentCustomer.getIsActive())){

                        String str = "10%";
                        shareProfitRecord(customer, parentCustomer.getId(), voucherBalance, bigDecimal10, orderNo, str);

                    }else if(parentCustomer.getLevelId() == 4 && "1".equals(parentCustomer.getIsActive())){

                        String str = "15%";
                        shareProfitRecord(customer, parentCustomer.getId(), voucherBalance, bigDecimal15, orderNo, str);

                    }else if(parentCustomer.getLevelId() == 5 && "1".equals(parentCustomer.getIsActive())){

                        String str = "20%";
                        shareProfitRecord(customer, parentCustomer.getId(), voucherBalance, bigDecimal20, orderNo, str);

                    }else if(parentCustomer.getLevelId() == 6 && "1".equals(parentCustomer.getIsActive())){

                        String str = "25%";
                        shareProfitRecord(customer, parentCustomer.getId(), voucherBalance, bigDecimal25, orderNo, str);

                    }

                    // 第二层
                    if(parentCustomer.getParentId() != null && parentCustomer.getParentId() != 1198 && parentCustomer.getLevelId() != 7){
                        Customer top3Customer = customerDao.queryById(parentCustomer.getParentId());
                        if(top3Customer != null){

                            if(top3Customer.getLevelId() == 1 && "1".equals(top3Customer.getIsActive())){

                            }else if(top3Customer.getLevelId() == 2 && "1".equals(top3Customer.getIsActive())){

                                String str = "3%";
                                shareProfitRecord(customer, top3Customer.getId(), voucherBalance, bigDecimal3, orderNo, str);

                            }else if(top3Customer.getLevelId() == 3 && "1".equals(top3Customer.getIsActive())){

                                String str = "6%";
                                shareProfitRecord(customer, top3Customer.getId(), voucherBalance, bigDecimal6, orderNo, str);

                            }else if(top3Customer.getLevelId() == 4 && "1".equals(top3Customer.getIsActive())){

                                String str = "9%";
                                shareProfitRecord(customer, top3Customer.getId(), voucherBalance, bigDecimal9, orderNo, str);

                            }else if(top3Customer.getLevelId() == 5 && "1".equals(top3Customer.getIsActive())){

                                String str = "12%";
                                shareProfitRecord(customer, top3Customer.getId(), voucherBalance, bigDecimal12, orderNo, str);

                            }else if(top3Customer.getLevelId() == 6 && "1".equals(top3Customer.getIsActive())){

                                String str = "15%";
                                shareProfitRecord(customer, top3Customer.getId(), voucherBalance, bigDecimal15_2, orderNo, str);

                            }

                            // 第三层
                            if(top3Customer.getParentId() != null && top3Customer.getParentId() != 1198 && top3Customer.getLevelId() != 7){
                                Customer top4Customer = customerDao.queryById(top3Customer.getParentId());
                                if(top4Customer != null){

                                    if(top4Customer.getLevelId() >= 3 && "1".equals(top4Customer.getIsActive())) {

                                        String str = "1%";
                                        shareProfitRecord(customer, top4Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                    }

                                    // 第四层
                                    if(top4Customer.getParentId() != null && top4Customer.getParentId() != 1198 && top4Customer.getLevelId() != 7){
                                        Customer top5Customer = customerDao.queryById(top4Customer.getParentId());
                                        if(top5Customer != null){

                                            if(top5Customer.getLevelId() > 3 && "1".equals(top5Customer.getIsActive())) {

                                                String str = "1%";
                                                shareProfitRecord(customer, top5Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                            }

                                            // 第五层
                                            if(top5Customer.getParentId() != null && top5Customer.getParentId() != 1198 && top5Customer.getLevelId() != 7){
                                                Customer top6Customer = customerDao.queryById(top5Customer.getParentId());
                                                if(top6Customer != null){

                                                    if(top6Customer.getLevelId() > 3 && "1".equals(top6Customer.getIsActive())) {

                                                        String str = "1%";
                                                        shareProfitRecord(customer, top6Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                    }

                                                    // 第六层
                                                    if(top6Customer.getParentId() != null && top6Customer.getParentId() != 1198 && top6Customer.getLevelId() != 7){
                                                        Customer top7Customer = customerDao.queryById(top6Customer.getParentId());
                                                        if(top7Customer != null){

                                                            if(top7Customer.getLevelId() > 3 && "1".equals(top7Customer.getIsActive())) {

                                                                String str = "1%";
                                                                shareProfitRecord(customer, top7Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                            }

                                                            // 第七层
                                                            if(top7Customer.getParentId() != null && top7Customer.getParentId() != 1198 && top7Customer.getLevelId() != 7){
                                                                Customer top8Customer = customerDao.queryById(top7Customer.getParentId());
                                                                if(top8Customer != null){

                                                                    if(top8Customer.getLevelId() > 4 && "1".equals(top8Customer.getIsActive())) {

                                                                        String str = "1%";
                                                                        shareProfitRecord(customer, top8Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                                    }

                                                                    // 第八层
                                                                    if(top8Customer.getParentId() != null && top8Customer.getParentId() != 1198 && top8Customer.getLevelId() != 7){
                                                                        Customer top9Customer = customerDao.queryById(top8Customer.getParentId());
                                                                        if(top9Customer != null){

                                                                            if(top9Customer.getLevelId() > 4 && "1".equals(top9Customer.getIsActive())) {

                                                                                String str = "1%";
                                                                                shareProfitRecord(customer, top9Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                                            }

                                                                            // 第九层
                                                                            if(top9Customer.getParentId() != null && top9Customer.getParentId() != 1198 && top9Customer.getLevelId() != 7){
                                                                                Customer top10Customer = customerDao.queryById(top9Customer.getParentId());
                                                                                if(top10Customer != null){

                                                                                    if(top10Customer.getLevelId() > 4 && "1".equals(top10Customer.getIsActive())) {

                                                                                        String str = "1%";
                                                                                        shareProfitRecord(customer, top10Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                                                    }

                                                                                    // 第十层
                                                                                    if(top10Customer.getParentId() != null && top10Customer.getParentId() != 1198 && top10Customer.getLevelId() != 7){
                                                                                        Customer top11Customer = customerDao.queryById(top10Customer.getParentId());
                                                                                        if(top11Customer != null){

                                                                                            if(top11Customer.getLevelId() > 5 && "1".equals(top11Customer.getIsActive())) {

                                                                                                String str = "1%";
                                                                                                shareProfitRecord(customer, top11Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                                                            }

                                                                                            // 第十一层
                                                                                            if(top11Customer.getParentId() != null && top11Customer.getParentId() != 1198 && top11Customer.getLevelId() != 7){
                                                                                                Customer top12Customer = customerDao.queryById(top11Customer.getParentId());
                                                                                                if(top12Customer != null){

                                                                                                    if(top12Customer.getLevelId() > 5 && "1".equals(top12Customer.getIsActive())) {

                                                                                                        String str = "1%";
                                                                                                        shareProfitRecord(customer, top12Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                                                                    }

                                                                                                    // 第十二层
                                                                                                    if(top12Customer.getParentId() != null && top12Customer.getParentId() != 1198 && top12Customer.getLevelId() != 7){
                                                                                                        Customer top13Customer = customerDao.queryById(top12Customer.getParentId());
                                                                                                        if(top13Customer != null){

                                                                                                            if(top13Customer.getLevelId() > 5 && "1".equals(top13Customer.getIsActive())) {

                                                                                                                String str = "1%";
                                                                                                                shareProfitRecord(customer, top13Customer.getId(), voucherBalance, bigDecimal1, orderNo, str);

                                                                                                            }

                                                                                                        }
                                                                                                    }

                                                                                                }
                                                                                            }

                                                                                        }
                                                                                    }

                                                                                }
                                                                            }

                                                                        }
                                                                    }

                                                                }
                                                            }

                                                        }
                                                    }

                                                }
                                            }

                                        }
                                    }

                                }
                            }

                        }
                    }

                }
            }

        }
    }

    public void shareProfitRecord(Customer customer, Integer parentUserId, BigDecimal voucherBalance, BigDecimal d,  String orderNo, String  str){
        Account parentAcc = accountDao.queryAccountByUserId(parentUserId);
        BigDecimal profit = voucherBalance.multiply(d).setScale(2, BigDecimal.ROUND_DOWN);
        if(profit.doubleValue() == 0){
            profit = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_DOWN);
        }
        parentAcc.setVoucherBalance(parentAcc.getVoucherBalance().add(profit));
        accountDao.update(parentAcc);

        AccountRecord ar = new AccountRecord();
        ar.setIntoUserId(parentUserId);
        ar.setOrderNo(orderNo);
        ar.setType("0");
        ar.setSign("1");
        ar.setUpdateTime(new Date());
        ar.setAmount(profit);
        ar.setNowAmount(parentAcc.getVoucherBalance());
        // ar.setInfo(customer.getAgentCode() + "参团成功! 您获取拼团红包" + str + "的奖励：" + profit);
        ar.setInfo(customer.getAgentCode() + "参团成功! 您获取拼团红包：" + profit);
        accountRecordDao.save(ar);
    }

    /**
     * 判断极乐桑巴拼团购买时的时间是否在规定时间范围内 TODO 处理团
     * 其余时间不处理团 TODO 处于等待中
     *
     * 每天 10-11:00    15-16:00    20-21:00
     */
    public boolean judgeCollageIsHandle() throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        // TODO 早上十点至十一点
        String time10 = time + " 10:00:00";
        Date date10 = sdf.parse(time10);

        Calendar begin10 = Calendar.getInstance();
        begin10.setTime(date10);

        String time11 = time + " 11:00:00";
        Date date11 = sdf.parse(time11);

        Calendar end11 = Calendar.getInstance();
        end11.setTime(date11);

        // TODO 下午三点至四点
        String time15 = time + " 15:00:00";
        Date date15 = sdf.parse(time15);

        Calendar begin15 = Calendar.getInstance();
        begin15.setTime(date15);

        String time16 = time + " 16:00:00";
        Date date16 = sdf.parse(time16);

        Calendar end16 = Calendar.getInstance();
        end16.setTime(date16);

        // TODO 晚上八点至九点
        String time20 = time + " 20:00:00";
        Date date20 = sdf.parse(time20);

        Calendar begin20 = Calendar.getInstance();
        begin20.setTime(date20);

        String time21 = time + " 21:00:00";
        Date date21 = sdf.parse(time21);

        Calendar end21 = Calendar.getInstance();
        end21.setTime(date21);

        Date date = new Date(); // 系统当前时间

        Calendar nowTime = Calendar.getInstance();
        nowTime.setTime(date);

        boolean temp = false;
        if( (nowTime.after(begin10) && nowTime.before(end11)) || (nowTime.after(begin15) && nowTime.before(end16))
                || (nowTime.after(begin20) && nowTime.before(end21)) ){
            temp = true;
        }
        return temp;
    }

}
